我正在利用尼康的API来控制显微镜。API是用C++编写的,而我是在C#中实现驱动程序的。要打开显微镜连接,我必须使用open与以下语法:
lx_result MIC_Open ( const lx_int32 iDeviceIndex, lx_uint64& uiConnectedAccessoryMask, const lx_uint32 uiErrMsgMaxSize, lx_wchar* pwszErrMsg)如果按照以下方式封送该技术,每当执行垃圾回收时,代码就会崩溃:
[DllImport("/filepath/Ni_Mic_Driver.dll")]
protected static extern int MIC_Open ( int deviceIndex , ref ulong accessoryMask , uint errorMessageMaxSize , [MarshalAsAttribute(UnmanagedType.LPWStr)] string error);引发0xc000005异常时,错误代码为80131506,指示垃圾收集器试图释放具有无效指针的对象。Visual 2013生成的错误消息指示:
“此错误可能是CLR或用户代码中不安全或不可验证的部分中的错误。此错误的常见来源包括COM-Interop或PInvoke的用户编组错误,这可能会损坏堆栈。”
按照消息通知,我将编组调整为以下内容,这不会导致CLR崩溃。
[DllImport("/filepath/Ni_Mic_Driver.dll")]
protected static extern int MIC_Open ( int deviceIndex , ref ulong accessoryMask , uint errorMessageMaxSize , [MarshalAsAttribute(UnmanagedType.LPStr)] string error);我感到困惑,因为我的理解是wchar*表示指向以空结尾的16位Unicode字符的字符串的指针,该字符串应该映射到UnamagedType.LPWStr。但是,只有当我使用UnmanagedType.LPStr时,代码才能工作。
以下内容也有效,但需要更多的工作才能提取相应的字符串。
[DllImport("/filepath/Ni_Mic_Driver.dll")]
protected static extern int MIC_Open ( int deviceIndex , ref ulong accessoryMask , uint errorMessageMaxSize , IntPtr errorPointer );对于为什么UnamagedType.LPWStr在使用UnmanagedType.LPStr或IntPtr时会导致崩溃,有什么想法吗?
发布于 2014-09-11 19:13:36
谢谢汉斯·帕桑特的推荐。我对编组进行了如下更正:
[DllImport("/filepath/Ni_Mic_Driver.dll")]
protected static extern int MIC_Open ( int deviceIndex , ref ulong accessoryMask , uint errorMessageMaxSize , [MarshalAsAttribute(UnmanagedType.LPWStr)] StringBuilder errorString);然后,我按照以下方式使用此方法(简化此处以供显示):
NikonDefinitions.accessory = 0;
int errorMessageCapacity = 256;
int nikonErrorMessageMaxSize = errorMessageCapacity - 1;
StringBuilder errorMessage = new StringBuilder(errorMessageCapacity);
int nikonReturn = NikonDefinitions.MIC_Open(Convert.ToInt32(1),ref NikonDefinitions.accessory,nikonErrorMessageMaxSize,errorMessage);https://stackoverflow.com/questions/25794620
复制相似问题