Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opaque pointers with PInvoke in C#

I am using a third party C library with the following opaque handle:

typedef struct _VendorHandle *VendorHandle;

Here is the vendor's C example of how to load the handle:

VendorHandle handle;
int err;
err = vendorLoadFile(&handle, "something.bin");

I am trying to call this method in C# with PInvoke using the following declaration:

[DllImport("VendorLib.dll")]
static extern int vendorLoadFile(IntPtr handle, string path);

Then I added the following code to use the declaration:

IntPtr handle = new IntPtr();
int code = vendorLoadFile(handle, path);

When I run it I'm getting the following error:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

I know that the DLL is fine and PInvoke is working because I am executing their vendorVersion() method so it has to be something else I'm doing wrong.

like image 812
Brent Matzelle Avatar asked Dec 26 '22 17:12

Brent Matzelle


1 Answers

That function takes a pointer to an opaque handle, so that it can write the handle into the memory pointed to by the pointer.
In C# terms, that's an out IntPtr:

[DllImport("VendorLib.dll")]
static extern int vendorLoadFile(out IntPtr handle, string path);

IntPtr handle;
int code = vendorLoadFile(out handle, path);
like image 99
SLaks Avatar answered Dec 28 '22 07:12

SLaks