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

标签 c# c++ marshalling

我有一个 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/

相关文章:

c# - 关闭 RabbitMQ 连接,即使应用程序没有正常结束

C++打印数组列表的元素

c# - 将 byte[] 转换为数组问题

c# - LinqToCRM 未正确转换

c# - 成员变量的 XML 序列化为 xmlnode

C# WinForms : Make panel scrollbar invisible

c# - 如何编码包含指向未知类型的 C 样式数组的第一个元素的指针的结构

c++ - 可变参数模板构造函数的推导指南失败

c++ - 如何运行 POCO C++ 服务器页面?

与 GWT 一起使用的 Json <-> Java 序列化