Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
调用C++;C#中的dll返回垃圾字符 我是C++新手。_C#_C++_Dll_Character - Fatal编程技术网

调用C++;C#中的dll返回垃圾字符 我是C++新手。

调用C++;C#中的dll返回垃圾字符 我是C++新手。,c#,c++,dll,character,C#,C++,Dll,Character,我正在开发一个简单的dll < >我必须从C++的C++函数中得到一个文件位置信息,它应该是字符串。 和C++将一些字符串返回到C ^。 这是我的密码 extern "C" __declspec(dllexport) const char* ParseData(char *filePath) { string _retValue(filePath); printf(_retValue.c_str()); //--> this prints ok return

我正在开发一个简单的dll

< >我必须从C++的C++函数中得到一个文件位置信息,它应该是字符串。

和C++将一些字符串返回到C ^。 这是我的密码

extern "C" __declspec(dllexport) const char* ParseData(char *filePath)
{
    string _retValue(filePath);

    printf(_retValue.c_str());  //--> this prints ok

    return _retValue.c_str();
}






[DllImport("D:\\Temp\\chelper.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ParseData(string s);


static void Main(string[] args)
{
    string s    = "D:\\Temp\\test.bin";
    string ret  = Marshal.PtrToStringAnsi(ParseData(s));
    Console.WriteLine(ret);
}

当我查看C++返回的字符串时,它看起来像下面。

硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼硼

我期待“d:\TEMP\Test.bin”,我把它传递给C++ DLL。
我的代码怎么了?

您的问题是试图返回一个局部变量。您的DLL可以访问该内存,因为它声明了变量,但C#程序无法访问它,因此它会收到垃圾。看看Windows API是如何实现的:让调用方传递一个缓冲区和该缓冲区的大小,然后将结果存储在那里。类似这样(未经测试):


或者直接使用传递的
文件路径
缓冲区。但是,无论您选择如何操作,都要确保将最终结果写入调用者提供的缓冲区,而不是局部变量。

您的问题是试图返回局部变量。您的DLL可以访问该内存,因为它声明了变量,但C#程序无法访问它,因此它会收到垃圾。看看Windows API是如何做到这一点的:让调用方传递一个缓冲区和该缓冲区的大小,然后将结果存储在那里。这可能会有所帮助:@thepirat000谢谢。我解决了这个URL的问题,你是想在C++中返回工作路径吗?它给了我另一个垃圾角色,比如붹5.不,您不应该返回workingPath。调用者应该为您提供一个缓冲区和该缓冲区的大小,然后您只需要将返回值放在该缓冲区中。试图从DLL返回局部变量会给您带来麻烦,因为调用者无法访问该内存。
extern "C" __declspec(dllexport) void ParseData(char* filePath, int pathSize)
{
  char workingPath[pathSize + 1]; //leave space for a trailing null

  strncpy(workingPath, filePath, pathSize);

  //do whatever parsing you need to do here

  strncpy(filePath, workingPath, pathSize);
}