我遇到以下问题:
我正在开发一个C#应用程序,该应用程序需要不安全的代码才能调用非托管的c++函数。结构为:
[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.
}
这就是我导入函数的方式:
[DllImport("imagedrv.dll", EntryPoint = "SendCommand", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
private static extern int SendCommand([MarshalAs(UnmanagedType.Struct, SizeConst = 8)]ref DataStruct s);
从线程成功调用了该函数,我得到了预期的结果,但是问题是每当我与Windows.Form表单进行交互时,整个应用程序就会崩溃。我将鼠标移到它上面或与contextmenustrip控件进行交互都没有关系。如果我不与表单进行交互,则程序可以正常运行。
通话示例:
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));
奇怪的是,如果我在项目属性中禁用了代码优化选项,则程序可以正常运行!
可能会发生什么?
最佳答案
您的buffer
数组正在被垃圾回收。
加
GC.KeepAlive(buffer);
在P / Invoke通话之后。
编辑:您还需要固定它。
关于c# - 启用“代码优化”选项时,应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3268574/