I'm having the following problem:
I'm developing a C# application which requires unsafe code to call an unmanaged c++ function. The structure is:
[StructLayout(LayoutKind.Sequential)]
unsafe struct DataStruct
{
public UInt16 index;
public UInt16 response;
public byte* addr; //this is a pointer to a byte array which stores some some data.
}
And this is how I import the function:
[DllImport("imagedrv.dll", EntryPoint = "SendCommand", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
private static extern int SendCommand([MarshalAs(UnmanagedType.Struct, SizeConst = 8)]ref DataStruct s);
The function is being called from a thread sucessfully and I get the开发者_运维技巧 expected results but the problem is whenever I interact with my Windows.Form form, the whole application crashes. It doesn't matter if I move the mouse over it or I interact with my contextmenustrip control. If I don't interact with the form, the program runs fine.
Example of call:
DataStruct s;
byte[] buffer = new byte[512];
s.index = 0x03;
s.response = 0;
fixed (byte* pBuffer = buffer) s.addr = pBuffer;
System.Console.WriteLine(SendCommand(ref s));
The weird thing is if I disable the code optimization option in my project properties, the program runs fine!
What could be happenning?
Try moving the SendCommand call inside the fixed block:
DataStruct s;
byte[] buffer = new byte[512];
s.index = 0x03;
s.response = 0;
fixed (byte* pBuffer = buffer) {
s.addr = pBuffer;
System.Console.WriteLine(SendCommand(ref s));
}
Otherwise, things could move around without you expecting it.
Your buffer
array is being garbage collected.
Add
GC.KeepAlive(buffer);
after the P/Invoke call.
EDIT: You also need to pin it.
精彩评论