[英]String to Char* Without memory leaks
I had try many ways to convert a string into a Char* but always got 2 errors when I import my DLL to a C# project. 我尝试了多种方法将字符串转换为Char *,但是将DLL导入C#项目时始终遇到2个错误。 the main function of my C++ DLL is like this:
我的C ++ DLL的主要功能是这样的:
//Example
extern "C" __declspec (dllexport) void Conv(std::string str)
{
FFileList file_list;
char temp_path[1024];
sprintf(temp_path,"%s*",arg_path);
GetFindFileListWin(temp_path,".mrs",file_list);
}
So, I Need to convert "str" to a char* because GetFindFileListWin
is like this: 因此,我需要将“ str”转换为char *,因为
GetFindFileListWin
如下所示:
GetFindFileListWin(char* path,char* ext,FFileList& pList);
and pass it to arg_path
. 并将其传递给
arg_path
。
I tried to do this: 我试图这样做:
char* arg_path = new char[str.length()+1];
strcpy(arg_path, str.c_str());
sprintf(temp_path,"%s*",arg_path);
delete[] arg_path;
but when I run Conv() in my C# program It says Windows has triggered a breakpoint in Program.exe. 但是当我在C#程序中运行Conv()时,它说Windows在Program.exe中触发了一个断点。 This may be due to a corruption of the heap, which indicates a bug in Program.exe or any of the DLLs it has loaded.
这可能是由于堆损坏所致,这表明Program.exe或其已加载的任何DLL中存在错误。 (Same happens if I use _strdup).
(如果使用_strdup,也会发生同样的情况)。 So, I tried in other way:
因此,我尝试了其他方式:
std::vector<char> Chr(str.size() + 1);
std::copy(str.begin(), str.end(), Chr.begin());
char *arg_path = &Chr[0];
sprintf(temp_path,"%s*",arg_path);
And I got Attempted to read or write protected memory message 而且我尝试读取或写入受保护的内存消息
My C# program do this: 我的C#程序这样做:
[DllImport("Mrs.dll")]
public static extern void Conv(string str);
public void Convert(TextBox Tx)
{
Conv(Tx.Text);
}
Hope someone could help me to solve this error, Thanks in advance. 希望有人能帮助我解决此错误,在此先谢谢您。
I suspect the asterisk in the sprintf statements could be causing the problem. 我怀疑sprintf语句中的星号可能是导致此问题的原因。 sprintf would expect a length parameter for the asterisk in the format string.
sprintf期望格式字符串中星号的长度参数。
sprintf(temp_path,"%s*",arg_path);
^
string is c++ object.So in dll it will not work 字符串是c ++对象。因此在dll中将不起作用
What you should do as I mentioned above just to do such 正如我上面提到的,您应该做的就是这样做
extern "C" __declspec (dllexport) void Conv(const char* str)
{
//do whatever
}
If your p/invoke signature is 如果您的p / invoke签名是
[DllImport("Mrs.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern void Conv(string str);
then your C++ declaration will be simply 那么您的C ++声明将很简单
extern "C" __declspec(dllexport) void Conv(const char* str);
and you won't need any std::string
at all. 而且您根本不需要任何
std::string
。
.NET and p/invoke do not know anything about std::string
. .NET和p / invoke对
std::string
一无所知。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.