在c#访问c ++ dll时尝试读取或写入受保护的内存错误

时间:2012-06-04 17:56:43

标签: c# c++ visual-c++ c#-4.0 interop

下面是c ++ dll类

class A
{
  public: 
   int __thiscall check(char *x,char *y,char *z);
  private:
   B *temp;
};

class B
{
  friend class A;
  Public:
   B();
   B(string x,string y,string z);
   ~B();
  private:
   string x;
   string y;
   string z;
};

c ++ dll方法定义如下

__declspec(dllexport) int __thiscall A::check(char *x,char *y,char *z)
{
  temp=new B(x,y,z); //getting error at this point when i am assigning memory to temp
  return 1;
}

c#dll import就像这样

[DllImport("MyDll.dll", CallingConvention = CallingConvention.ThisCall, ExactSpelling = true, EntryPoint = "check")]
public static extern int check(IntPtr val,string x,string y,string z);

c ++ dll build工作正常,但是当c#调用c ++ dll方法时它也看起来很好,当它进入函数时,在方法的第一行中,它尝试为临时指针创建内存,该指针已在类A中声明为B类的指针是私有的。它给出的错误是

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

2 个答案:

答案 0 :(得分:0)

__declspec(dllexport)应该在课堂上(例如,课程__declspec(dllexport) MyClass),而不是其成员方法。

入口点应该是一个受损的C ++名称(例如2@MyClass@MyMethod?zii),而不是“check”。 您可以使用Depends.exe查找名称。

答案 1 :(得分:0)

我发现了问题,问题在于c ++中的check函数。应该像这样创建temp。

int __thiscall A::check(char *x,char *y,char *z)
{
  A *xyz=new A();
  A->temp=new B(x,y,z); // doing this eliminates the issue.
  return 1;
}

感谢所有帮助过我的人。