启用代码优化选项时应用程序崩溃
我遇到以下问题:
我正在开发一个 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));
奇怪的是,如果我在项目属性中禁用代码优化选项,程序运行正常!
可能会发生什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试将 SendCommand 调用移动到固定块内:
否则,事情可能会在您意想不到的情况下移动。
Try moving the SendCommand call inside the fixed block:
Otherwise, things could move around without you expecting it.
您的
buffer
数组正在被垃圾回收。添加
在 P/Invoke 调用之后
。 编辑:您还需要将其固定。
Your
buffer
array is being garbage collected.Add
after the P/Invoke call.
EDIT: You also need to pin it.