title: System.Access Violation Exception While calling C++ Dll in .Net Application
body: <p>I am implementing C++ Dll in the C#.</p>
  
  <p>My Wrapper.h file:</p>
  
  <p>`</p>
  
  <pre><code>    class __declspec(dllexport) TestClass
       {   
        public:
                int value;
                TestClass(int value):value(value)
                {
                }
               ~TestClass()
                {
                }
       }
  </code></pre>
  
  <p>`</p>
  
  <p>My Wrapper.cpp File</p>
  
  <pre><code>   #include "stdafx.h"
  
     #include "WrapperApplication.h"
  </code></pre>
  
  <p>My C# code</p>
  
  <pre><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
  }
  </code></pre>
  
  <p>My TestStruct.cs file:</p>
  
  <pre><code> [StructLayout(LayoutKind.Sequential, Pack = 4)]
    public unsafe struct TestStruct
    {
      public IntPtr* vtable;
      public int value;
    }
  </code></pre>
  
  <p>I have to Call CPP dll with the help of the <strong>Vtable</strong> 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   <strong>Test(_testStruct, value);</strong> 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.</p>