问题描述
在c ++中有以下类别
in c++ i have these below classes
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方法是这样的
my dll method in c++ is like this
__declspec(dllexport) int __thiscall A::check(char *x,char *y,char *z)
{
temp=new B(x,y,z);
return 1;
}
B()构造函数的代码如下:
code for B() constructor is below:
B::B(string x, string y,string z)
{
.......
}
下面提到的是我的c#dll import
below mentioned is my c# dll import
[DllImport("sour.dll", CallingConvention = CallingConvention.ThisCall, ExactSpelling = true, EntryPoint = "check")]
public static extern void check(IntPtr val,string x,string y,string z);
c ++构建成功,没有任何错误,但是当我从c#使用dll import方法我得到这下面的错误时,我试图分配内存temp类指针。下面提到的是错误。
the c++ build went successful with out any errors, but when i call this method from c# using dll import method i am getting this below error when i am trying to assign memory for "temp" class pointer. Below mentioned is the error.
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
任何人都可以帮忙。提前感谢。
Can any one please help on this. Thanks in advance.
推荐答案
我假设导出方法而不是类成员更容易。
请确保DllImport使用正确的调用约定。
I would assume exporting methods instead of class members is easier.Please make sure that the DllImport uses the correct calling convention.
__declspec(dllexport) void __cdecl check(int x)
public partial class NativeMethods {
/// Return Type: void
///x: int
[System.Runtime.InteropServices.DllImportAttribute("<Unknown>", EntryPoint="check", CallingConvention=System.Runtime.InteropServices.CallingConvention.Cdecl)]
public static extern void check(int x) ;
}
你确保32/64位版本的DLL匹配。如果您运行x86 .net版本(32位),您可以激活本机代码和托管代码的调试,您应该能够在C ++方法中设置断点,以了解会发生什么。
Did you make sure that 32/64 bit version of your dll matches. If you run the x86 .net version (32bit) you can activate debugging of native and managed code and you should be able to set a break point in your C++ method to see what happens.
这篇关于在调用c ++代码时,获取访问冲突错误是c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!