C# 'String' 到 C++ 'std::string'

C# 'String' to C++ 'std::string'

我有一个 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# 中获取一个简单的字符串到 std::string 在 C++ 中,那就太好了。

或者给我一个提示,通过 std::printf( ) 将打印的字符串保存在 std::string.

类型的变量中

根据 the documentation,C# 将 string 对象编组为简单的 "pointer to a null-terminated array of ANSI characters" 或 C++ 术语中的 const char *

如果将 GetOutputString 的 typedef 更改为 return a const char *,一切都会正常。

带有 CLI 的 C++,使用 System::String^(这是一个 .Net 字符串,即与 C# 相同)

using GetOutputString = System::String^ (__stdcall *) ();

那你可以这样做

std::string standardString = context.marshal_as<std::string>(managedString);

(信用 [)