Search code examples
c#c++unmanagedmanaged

System.Access Violation Exception While calling C++ Dll in .Net Application


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.


Solution

  • 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:

    • Give your DLL a flat C interface, or a Component Object Model (COM) interface. This will make it callable from most platforms and languages.
    • Keep the DLL as-is, but call it from C++/CLI code instead of C# code. It's the reason C++/CLI exists, after all: To make this kind of glue code between .Net Framework applications and unmanaged libraries.