c# - 使用非托管导出将字符串从C#返回C++会返回数字

标签 c# c++ return-type unmanagedexports

我在C#中有一个函数,使用Unmanaged Exports从C++调用。在C#中正确接收了传递的字符串,但在C++中返回的字符串显示为数字,例如5073480。这可能是什么问题?我需要用C++重新获取字符串。以下是代码

C++代码:

using Testing = wchar_t*(__stdcall *) (wchar_t* name);
int _tmain(int argc, _TCHAR* argv[])
{
    HMODULE mod = LoadLibraryA("CSharp.dll");
    Testing performTest = reinterpret_cast<Testing>(GetProcAddress(mod, "testing"));
    wchar_t* d_str = L"JS";
    wchar_t* result = performTest(d_str);
    std::printf("Result from c#: %d\n", result);
    getchar();
    return 0;
}

C#代码:
[DllExport(ExportName = "testing", CallingConvention = CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.LPWStr)]
public static string PassStringInOut([MarshalAs(UnmanagedType.LPWStr)]string name)
{
    Console.WriteLine("Received string is: "+name);
    return string.Format("Hello from .NET assembly, {0}!", name);
}

最佳答案

这里有几个问题。

格式字符串错误。要使用ASCII版本的printf打印Unicode字符串,指定的格式为%S(注意大写的S)。

其次,您在这里引入了内存泄漏。在C++中使用完字符串后,您必须通过调用CoTaskMemFree释放内存(假设您正在编写Windows的代码)。

关于c# - 使用非托管导出将字符串从C#返回C++会返回数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51911279/

相关文章:

c# - 无法分配给方法组

c++ - GlobalMemoryStatusEx 不考虑新阵列

c++ - 强制窗口位于最顶层的窗口之上(如任务管理器)

java - 从 java 中的 lambda forEach() 返回

java - 如何根据条件返回 json 响应并重定向到其他 View ?

c++ - 使用引用作为返回值是否被认为是错误的编码风格?

C# GetHashCode() 用例和文档说明

c# - 使用 HTTP Post 发送大数据时出错

c# - 如何在 C# 中查找 IIS 站点 ID?

c++ - 如何调用模板中定义的函数