[英]Access Violation when returning a value calling a C++ dll function from C#
我正在尝试从 C# 调用 DLL 中的 C++ 函数。 这个函数的一个参数是一个指向短型变量的指针。
我没有做任何花哨的数据结构或未知大小的变量。 只是一个简单的短值。
当 DLL c++ 函数尝试修改此变量的值时,它会给出“非托管异常 0xC0000005:访问冲突”。
我无法修改 DLL 源代码(它在其他项目中使用,我无法触摸它,尽管我有调试它的源代码)
c++ DLL函数的代码(请注意代码中的“//this line provokes the exception”注释行)
// declaration
virtual TestFunction(short __RPC_FAR *sRet) = 0;
// definition
STDMETHODIMP CABTest::TestFunction(short *sReturnValue)
{
//some
//calculations
//here
*sReturnValue = 1; //this line provoques the exception
return 0;
}
调用 DLL 的 C# 代码
[DllImport("test.dll", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
static extern short TestFunction(ref short sReturn);
short sMyValue = 0;
TestFunction(ref sMyValue);
我希望 sMyValue 值为 1,因为我传递的引用是直接的短类型(不是花哨的数据结构),但我只遇到应用程序崩溃(上述例外)。
我可以在 C# 代码中做些什么来避免这个问题? 我所看到的所有搜索类似问题都需要重写 C++ 函数(将“short *sReturnValue”更改为“short **sReturnValue”,但我无法触及原始 DLL 源代码。
我想我会写一个调用 test.dll 的 wrapper.dll,但我想知道是否有任何直接和更快的解决方案。
我按照@PaulMcKenzie 的建议创建了一个实例,并且运行良好。 我错误地认为我可以只获取 DLL 并使用所需的计算函数,但我想我不能。 只是将这个答案留给可能犯同样错误的其他人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.