Posts

Showing posts with the label pinvoke

Using more complicated PInvoke calls

In my last blog post I covered using a very basic PInvoke call to an unmanaged dll that returned an integer. For basic data types int, char, double, float, etc you don't need to do any manual marshaling. However, especially with the Win32 API you will find yourself needing to use more complicated types. Even getting a string back from an unmanaged dll takes more work, and then we have classes, structs, arrays, etc we need to deal with. Let's look at some unmanaged dll signatures extern "C" { struct { char* NAME, char* ADDRESS, int age } PERSON; void FillByteArray( unsigned char* byteArray, int arrayLength ); const char* GetLastErrorMessage(); void FillAStruct( PERSON* pPerson ); } Now here we have three functions; one fills a byte array, one returns a string, and another modifies a struct we've defined. Nothing complicated on the C++ side but we need to be careful when we start using pinvoke to call these functions...

C# using PInvoke to call an unmanaged DLL

Recently I've found myself having to do some pinvoking with .net. Microsoft offers an excellent primer on the subject. http://msdn.microsoft.com/en-us/library/aa288468(v=vs.71).aspx For it's many great benefits the .net framework doesn't do everything. You will find yourself having to invoke a win32 API function call at some point in your career. I'm going to offer some quick and dirty samples on getting data back and forth using the platform invoke. First you cannot invoke any classes using pinvoke. You get 1 function call at a time. If you want classes you will need to write a custom CLI/C++ wrapper. But that goes beyond the scope of this post. First let's look at the unmanaged\win32 side of things. Let's say you have a dll called MyDll.dll. In this dll you have a bunch of functions. // this lets use export functions from the dll #define DllExport __declspec( dllexport ) // first we use extern "C" so we don't get name mang...