I am implementing C++ Dll in the C#.
My Wrapper.h file:
`
class __declspec(dllexport) TestClass
{
public:
int value;
TestClass(int value):value(value)
{
}
~TestClass()
{
}
}
`
My Wrapper.cpp File
#include "stdafx.h"
#include "WrapperApplication.h"
My C# code
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
}
My TestStruct.cs file:
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public unsafe struct TestStruct
{
public IntPtr* vtable;
public int value;
}
I have to Call CPP dll with the help of the Vtable in the .Net Application. I have created TestStruct.cs file as replica of My Cpp class. And trying to Call the CPP constructor in the C# constructor. But at the line Test(_testStruct, value); throws the System.AccessViolation Exception as Attempted to read or Write the memory.It is often indication that other memory is corrupt. The values for _teststruct, value in the Test ctor comes but still it throws the Exception.I have tried many ways but failed to get the solution. Please let me know where I am wrong in the implementaion. So Any Help would Appreciated.
I think the easiest way would be not to call directly a C++-interface DLL from C#. With this premise, two ways appear before you: