C# 调用C++DLL的问题“尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”

我用C#开发一个项目,需要饮用C++ 的DLL,但是调用其中的方法是有几个函数正常,有一些方法总是报错。
错误为:“尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”
哪位大神可以帮我看看。
这是DLL中的方法:
typedef struct ehInformation
{
std::string ehfilename;
std::string mark; //eh头文件的标示
std::string sendAddr; //eh头文件的发送地址
std::vector<std::string> recvAddrs; //eh头文件的接收地址
std::string type; //eh头文件的类型
std::string content; //eh头文件的发送内容
std::vector<std::string> attachs; //eh头文件的附件
std::string status; //邮件状态(ehr文件使用)
}EHINFOR;

typedef int DmailHandle;
int dmail_create(DmailHandle handle, EHINFOR& ehinfo, std::string& errdesc, int flag = 0);
以下是C#代码:
public struct ehInformation
{
public string ehfilename;
public string mark; //eh头文件的标示
public string sendAddr; //eh头文件的发送地址
public ArrayList recvAddrs;
//public string[] recvAddrs; //eh头文件的接收地址
public string type; //eh头文件的类型
public string content; //eh头文件的发送内容
public ArrayList attachs;
//public string[] attachs; //eh头文件的附件
public string status; //邮件状态(ehr文件使用)
}
[DllImport("dmailnewclient.dll", EntryPoint = "?dmail_create@@YAHAAIAAUehInformation@@AAV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H@Z", CharSet = CharSet.Ansi,SetLastError = true, CallingConvention = CallingConvention.StdCall)]
public static extern int Dmail_Creat(uint handle, ehInformation ehInfor, string errdesc, UInt16 flag = 0);
调用:
string errdesc ="111";
int temp = dmailnewclient.Dmail_Creat(t,ehinfo, errdesc);

两边string不是同一个类型,不能通用。

C#无法正确使用C++的string类型。
C++那边应该改为const char*或者const wchar_t*
如果用前者,C#那边CharSet要改为ANSI
温馨提示:内容为网友见解,仅供参考
第1个回答  2014-09-01
ehInformation 加Layout

传参加ref追问

啥意思?在哪加?

追答

http://msdn.microsoft.com/zh-cn/library/aa288468%28v=vs.71%29.aspx

相似回答