【发布时间】:2010-07-16 20:19:49
【问题描述】:
我遇到以下问题:
我正在开发一个 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));
奇怪的是,如果我在项目属性中禁用代码优化选项,程序运行正常!
会发生什么?
【问题讨论】:
标签: c# optimization crash unmanaged