Below is another “hello world” example. Rather than “puts” which writes to a console window, this example calls the windows MessageBox function, provided as part of the Win32 API in USER32.DLL:
#import <mscorlib.dll> // to get Microsoft::Runtime::String typedef void* HWND; [sysimport(dll="user32", charset="ansi")] extern "C" int MessageBox(HWND hWnd, String* pText, String* pCaption, unsigned int uType); void main(void) { String* pText = L"Hello World!”; String* pCaption = L"PInvoke Test"; MessageBox(0, pText, pCaption, 0); }
Notice that the function is declared as MessageBox, even though USER32.DLL exports only MessageBoxA and MessageBoxW (but no MessageBox). PInvoke notes that you specified a charset of ”ansi”, and therefore looks for “MessageBoxA” if it cannot find “MessageBox”. Similarly, if you had specified charset=”unicode”, PInvoke would have found MessageBoxW for you automatically. [charset therefore specifies two types of behaviour – how PInvoke marshals text strings, and how it looks up function names in the DLL. It is possible to have the first, without the second, by setting a “NoMangle” flag. This is used implicitly by VB7, but not exposed by the VC7 compiler]