Interop Callback, Returning an Array of Bytes (BYTE**)  
Author Message
Steve Graber





PostPosted: Common Language Runtime, Interop Callback, Returning an Array of Bytes (BYTE**) Top

I am writing a .Net wrapper around a custom native dll for Windows. One of the interfaces to the custom native dll includes a callback routine. The callback routine includes a parameter that is a structure with an embedded BYTE** which is used to pass data back to the caller in the custom native dll. I have laid out the structure in the .Net wrapper using the 'StructLayout(LayoutKind.Explicit)' to get the structure members aligned correctly to what is passed in from the native dll. This works correctly. I am creating a buffer using System.Runtime.InteropServices.Marshal.AllocHGlobal. I am assigning the BYTE** to the buffer using the following code (unsafe)...

byte** pmsgBuf = (byte**)sServ.msgBuf;
byte* pBuf2 = (byte*)bufptr;
*pmsgBuf = pBuf2;
ushort* pSize = (ushort*)sServ.msgSize;
*pSize = size;

Where bufptr is the memory allocated by AllocHGlobal, size is the size of the data in the buffer, and sServ is the data structured passed into the callback.

This code seems to all work perfectly fine. The data gets copied into the buffer and the native dll reads the data correctly. However, I get the error :"System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt". This error always happens the 2nd time I return data to the native dll using the same buffer. Also, I am writing logging information out to a file from the main .Net application using StreamWriter. If I run the application without using the StreamWriter to log data, the application runs successfully (10 loops through the test). This failure happens the same every time I run the app.

Does anyone have any ideas about what is causing this error

Thank you for your help,

Steve



.NET Development22  
 
 
Steve Graber





PostPosted: Common Language Runtime, Interop Callback, Returning an Array of Bytes (BYTE**) Top

Apparently the callback was getting garbage collected. I created global scope delegates to the callback functions and at the start of main initialized them. Then I passed the delegates into the native dll interface. This fixed the problem.