【发布时间】:2018-09-21 06:42:50
【问题描述】:
我有一个用 C++ 编写的本机(非托管).dll,它将从托管进程(C# 程序)中调用。在调试 dll 时,我发现的问题是,当我在 dll 中使用 new 关键字创建对象时,出现系统访问冲突异常。这仅在从托管进程调用 dll 时出现,而不是在我从另一个本机程序调用它时出现。
代码是这样的:
// Native.dll file
MyClass myInstance; // global variable (and does need to be so)
__declspec(dllexport) uint8_t _stdcall NativeFunction(){
myInstance = new MyClass(); // <-- this causes Access Violation Exception
}
和 C# 代码:
using System.Runtime.Interopservices;
// Loading the dll
[DllImport("Native.dll",CallingConvention = CallingConvention.StdCall)]
private extern static byte NativeFunction();
class TestClass{
byte returnVal = NativeFunction(); //<-- exception in managed context
}
我知道这与试图在允许的内存空间之外分配内存的本机进程有关。仅当使用new(至少在这个项目中)分配内存时才会发生这种情况,不幸的是我确实需要使用它。我的问题是:有谁知道为什么会导致异常以及如何避免它?
【问题讨论】:
标签: c# c++ interop access-violation interopservices