views:

57

answers:

2

Hello, 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?

+2  A: 

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.

Mike Caron
A: 

Your buffer array is being garbage collected.

Add

GC.KeepAlive(buffer);

after the P/Invoke call.

SLaks
Thank you for your answers.As SLaks pointed, my buffer was being garbage collected and his line of code fixed my problems. Thanks!
santiageitorx