Ports benutzen (VB)

Aus der Mikrocontroller.net Artikelsammlung, mit Beiträgen verschiedener Autoren (siehe Versionsgeschichte)
Wechseln zu: Navigation, Suche

Allgemein

Ich wurde mal gefragt ob es möglich seie, unter Visual Basic auf die Ports des PCs zuzugreifen. Hier veröffentliche ich meine Antwort.

Der Zugriff erfolgt über eine DLL Datei, die selber giveIO benutzt. Das setzt natürlich voraus dass dieses auch installiert ist.

Die nötige DLL Datei

Der Quellcode

#include <windows.h>
#include <stdint.h>

uint8_t _inb( uint16_t portaddr )
{
  uint8_t value;

  asm volatile
  (
    "in %1, %0" :
    "=a" (value) :
    "d" (portaddr)
  );

  return value;
}

void _outb( uint8_t value, uint16_t portaddr )
{
  asm volatile
  (
    "out %1, %0" ::
    "d" (portaddr), "a" (value)
  );
}

bool _iopl()
{
  bool ret;

  HANDLE h;
  h = CreateFile("\\\\.\\giveio", GENERIC_READ,
    0, NULL, OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL, NULL);

  ret = h != INVALID_HANDLE_VALUE;
  CloseHandle(h);

  return ret;
}


extern "C" __declspec(dllexport) char _stdcall inb( int portaddr )
{
  return _inb( portaddr );
}

extern "C" __declspec(dllexport) void _stdcall outb( int portaddr, char value )
{
  _outb( value, portaddr );
}

extern "C" __declspec(dllexport) bool _stdcall iopl()
{
  return _iopl();
}


BOOL APIENTRY DllMain (HINSTANCE hInst, DWORD reason, LPVOID reserved )
{
  return TRUE;
}


Den Code kompilieren

g++.exe -c dllmain.cpp -o dllmain.o -I"lib/gcc/mingw32/3.4.2/include"  -I"include/c++/3.4.2/backward"  -I"include/c++/3.4.2/mingw32"  -I"include/c++/3.4.2"  -I"include"  -DBUILDING_DLL=1
dllwrap.exe --output-def libVBgiveio.def --driver-name c++ --implib libVBgiveio.a dllmain.o  -L"lib" --no-export-all-symbols --add-stdcall-alias  -o VBgiveio.dll


Die für VB nötigen Declares

DLL Datei im Systemverzeichnis

Private Declare Sub outb Lib "VBgiveio.dll" (ByVal portaddr As Long, ByVal value As Byte)
Private Declare Function inb Lib "VBgiveio.dll" (ByVal portaddr As Long) As Byte
Private Declare Function iopl Lib "VBgiveio.dll" () As Boolean

DLL Datei im Anwendungsverzeichnis

Private Declare Sub outb Lib ".\VBgiveio.dll" (ByVal portaddr As Long, ByVal value As Byte)
Private Declare Function inb Lib ".\VBgiveio.dll" (ByVal portaddr As Long) As Byte
Private Declare Function iopl Lib ".\VBgiveio.dll" () As Boolean

Benutzen des Codes unter VB

Nunja, das ergibt sich eigentlich schon zu 100% aus den Declares.