Platform invoke
Earlier in this chapter, we implemented a handle wrapper class that used a Windows API function, CloseHandle()
, to delete system handles when the object was disposed of. The way a C# program can invoke Windows APIs, but also any function exported from a native dynamic-linked library (DLL), is done through Platform Invocation Services, also known as Platform Invoke or P/Invoke.
P/Invoke locates and invokes an exported function and marshals the arguments between the managed and unmanaged boundaries. In order to be able to call a function using P/Invoke, you must know the name and signature of the function, as well as the name of the DLL from where it is exported. Then, you must create a managed definition of the unmanaged function. To understand how this works, we will look at an example of the MessageBox()
function, available in user32.dll
. The function signature is as follows:
int MessageBox(HWND hWnd, LPCTSTR lpText, Â Â Â Â Â Â Â ...