C#调用C++dll 如何返回char* str[]
用C#调用C++dll,如何返回char*str[](字符串数组,C#中的string[])...
用C#调用C++dll,如何返回char* str[](字符串数组,C#中的string[])
展开
3个回答
展开全部
COM中最标准的做法应该是
从C++处返回一个SAFEARRAY,元素类型是BSTR
c++代码:
#include <windows.h>
#include <oaidl.h>
#pragma comment(linker, "/export:GetStrArr=_GetStrArr@0")
extern "C" SAFEARRAY* APIENTRY GetStrArr()
{
SAFEARRAY* r;
SAFEARRAYBOUND b;
b.lLbound = 0;
b.cElements = 3;
r = SafeArrayCreate(VT_BSTR, 1, &b);
LONG i;
i = 0;
SafeArrayPutElement(r, &i, SysAllocString(L"aaaaa"));
i = 1;
SafeArrayPutElement(r, &i, SysAllocString(L"ababc"));
i = 2;
SafeArrayPutElement(r, &i, SysAllocString(L"cbcbc"));
return r;
}
C#代码
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport("a.dll")]
[return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)]
extern static string[] GetStrArr();
static void Main(string[] args)
{
foreach(string s in GetStrArr())
Console.WriteLine(s);
}
}
展开全部
/ Inclusion guard
#ifndef _DLLTUT_DLL_H_
#define _DLLTUT_DLL_H_
// Make our life easier, if DLL_EXPORT is defined in a file then DECLDIR will do an export
// If it is not defined DECLDIR will do an import
#if defined DLL_EXPORT
#define DECLDIR __declspec(dllexport)
#else
#define DECLDIR __declspec(dllimport)
#endif
// Specify "C" linkage to get rid of C++ name mangeling
extern "C"
{
// Declare 2 functions
DECLDIR int Add( int a, int b );
DECLDIR void Function( void );
DECLDIR void GetPrt( char * prtStr );
}
// End the inclusion guard
#endif
static void Main(string[] args)
{
test.Function();
Console.WriteLine("result: " + test.Add(2, 3).ToString());
//string str = "aaddddddddddd";
byte[] str = new byte[12];
test.GetPrt(ref str[0]);
Console.WriteLine(System.Text.Encoding.GetEncoding("GB2312").GetString(str));
Console.ReadLine();
}
}
class test
{
[DllImport("..\\..\\lib\\DLLTest.dll")]
public static extern void Function();
[DllImport("..\\..\\lib\\DllTest.dll")]
public static extern int Add(int i,int j);
[DllImport("..\\..\\lib\\DllTest.dll")]
public static extern void GetPrt(ref byte prtStr);
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
这种一般用 out string[] s 加 out关键字。
追问
这个方法已经试过了,不行啊,也不报错,但程序直接跳出
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询