我有一个 C# DLL,具有以下功能:
[DllExport(ExportName = "getOutputString", CallingConvention = CallingConvention.StdCall)]
public static String getOutputString()
{
String managedString = "123456789012345678901234567890";
return managedString;
}
和一个 C++ 应用程序将上述函数用作:
HMODULE mod = LoadLibraryA("MyCustomDLL.dll");
using GetOutputString = std::string (__stdcall *) ();
GetOutputString getOutputString = reinterpret_cast<GetOutputString>(GetProcAddress(mod, "getOutputString"));
并希望将 DLL 中的字符串存储在 C++ 变量中:
std::string myVariable = getOutputString();
当我运行 C++ 应用程序时,它崩溃了。
但是当我只使用 std::printf 中的函数时,代码工作得很好:
std::printf("String from DLL: %s\n", getOutputString());
我的实际任务是从 DLL 中获取一个字符串数组,但如果您能帮助我从 C# 中获取一个简单的字符串到 C++ 中的 std::string,那就太好了。
或者只是给我一个提示,通过 std::printf( ) 将打印的字符串保存在一个 std::string 类型的变量中。
最佳答案
根据 the documentation , C# 将 string
对象编码(marshal)为简单的“指向以空字符结尾的 ANSI 字符数组的指针”,或者用 C++ 术语表示为 const char *
。
如果您更改 GetOutputString
的 typedef 以返回一个 const char *
,一切都会正常。
关于C# 'String' 到 C++ 'std::string',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56947676/