C#调用C++写的dll,返回字符串
记录工作时自己遇到的一些问题
有两种方案:
一是C#传递一个ref参数给c++,在c++内把字符串拷贝到传进来的ref参数中。但这个方案有一个缺点:必须提前设置好字符串的长度。在字符串长度无法预估的情况下不好用。
二是把字符传作为返回值返回,本文采用第二种方案
提示:以下是本篇文章正文内容,下面案例可供参考
一、C++部分
代码如下(示例):
wchar_t* __cdecl returnStr
(
int argc,
wchar_t* args[]
)
{
//xxxxxx
//一些处理
//xxxxxx
wstring aaa;
size_t size = aaa.str().capacity();
static wchar_t* ret = new wchar_t[size];
wcscpy_s(ret, size, aaa.str().c_str()); //必须把字符串拷贝到new的内存里 否则返回后指针指向的内存空间会被销毁
return ret;
二、C#部分
使用IntPtr类型接收字符串指针,然后用Marshal解析回字符串。代码如下
[DllImport("mydll.dll", EntryPoint = "returnStr", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl , CharSet = CharSet.Unicode)]
public static extern IntPtr GetStrDll(int arg , string[] args);
static public string ExecDll(string path)
{
string[] args = { "abc", "123" }; //模拟传递一些参数
string output = Marshal.PtrToStringUni(GetStrDll(2, args));
return output;
总结
C++dll向C#传递参数时,如果类型不同可以使用Intptr或者byte[]进行接收。