将字符数组从C ++ dll返回到C# [英] Return a char array from C++ dll to C#

查看:472
本文介绍了将字符数组从C ++ dll返回到C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以创建将c ++ dll中的char数组返回到c#中的char数组或字符串的函数?

Is there any way to create a function that returns a char array from c++ dll to a char array or string in c#?

推荐答案

在您的C ++ DLL中:
In your C++ DLL:
__declspec(dllexport) TCHAR* __cdecl testString();

__declspec(dllexport) TCHAR* testString()
{
    return _T("Wheee!");
}



要从您的C#调用它,您需要执行以下操作:



And to call it from your C# you need to do something like:

class Program
{
[DllImport("MyDLL.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr testString();

void CallCppDLL()
{
IntPtr t = testString();
String result = Marshal.PtrToStringAuto(t);
}
}



我已经有一段时间没有这样做了,所以请随时纠正我:)



I haven''t done this in quite some time, so feel free to correct me :)


它不起作用,因为返回地址是局部变量...
还有其他想法吗?
It doesn''t work because the returning address is of a local variable...
any other ideas?


这篇关于将字符数组从C ++ dll返回到C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆