我在 C# 中实现 C++ Dll。
我的 Wrapper.h 文件:
`
class __declspec(dllexport) TestClass
{
public:
int value;
TestClass(int value):value(value)
{
}
~TestClass()
{
}
}
`
我的 Wrapper.cpp 文件
#include "stdafx.h"
#include "WrapperApplication.h"
我的 C# 代码
public unsafe class Message:IDisposable
{
private TestStruct* _testStruct;
private IntPtr* _oldVTable;
[DllImport(@"WrapperApplication.dll", EntryPoint = "??0TestClass@WrapperApplication@@QAE@H@Z", CallingConvention = CallingConvention.ThisCall)]
extern static IntPtr Test(TestStruct* testStruct, int value);
public Message(int value)
{
_testStruct=(TestStruct*)Memory.Alloc(sizeof(TestStruct));
Test(_testStruct, value);
}
#region IDisposable Members
public void Dispose()
{
//throw new NotImplementedException();
}
#endregion
}
我的 TestStruct.cs 文件:
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public unsafe struct TestStruct
{
public IntPtr* vtable;
public int value;
}
我必须借助 .Net 应用程序中的 Vtable 调用 CPP dll。 我创建了 TestStruct.cs 文件作为我的 Cpp 类的拷贝。 并尝试在 C# 构造函数中调用 CPP 构造函数。 但是在 Test(_testStruct, value); 行抛出 System.AccessViolation Exception as Attempted to read or Write the memory.It is often indication that other memory is corrupt. _teststruct 的值,Test ctor 中的值来了,但它仍然抛出异常。我尝试了很多方法但未能获得解决方案。请让我知道我在实现中哪里错了。 因此,我们将不胜感激。
最佳答案
我认为最简单的方法是不直接从 C# 调用 C++ 接口(interface) DLL。有了这个前提,两条路就出现在你面前:
- 为您的 DLL 提供平面 C 接口(interface)或组件对象模型 (COM) 接口(interface)。这将使它可以从大多数平台和语言调用。
- 保持 DLL 不变,但从 C++/CLI 代码而不是 C# 代码调用它。毕竟,这就是 C++/CLI 存在的原因:在 .Net Framework 应用程序和非托管库之间制作这种胶水代码。
关于c# - 在 .Net 应用程序中调用 C++ Dll 时出现 System.Access 冲突异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19178376/