永发信息网

C#调用C++dll 如何返回char* str[]

答案:3  悬赏:0  手机版
解决时间 2021-11-28 01:37
C#调用C++dll 如何返回char* str[]
最佳答案
/ 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关键字。追问这个方法已经试过了,不行啊,也不报错,但程序直接跳出

COM中最标准的做法应该是

从C++处返回一个SAFEARRAY,元素类型是BSTR

c++代码:
#include 
#include 
#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);
    }
}
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
四五运动的学生怎么死的?
唐冶新区离济南新东站多远
高中数学找规律2.7.15.26.40过程 A1=2 A2=7
QQ for PSP1.5无法登陆账号
荣耀6手机dts模式是什么意思?需要打开吗?
潜到海水下50m的潜水员,受到海水的压强多大
怎么还原一张被涂改的照片 用QQ修改的
粤语进贡法兰西是什么意思
成浯大全四字成浯虚与萎蛇
周六领导微信群下通知组织足球赛,受伤算工伤
献字开头字成语
仁寿县到双流县大林镇,大林车站公交车怎么做
橙光游戏民国 残阳 宋自强。。游戏大概内容(
新款一加手机联发科cpu售价330怎么样
维修平台哪个比较好用?
推荐资讯
莞城罗沙罗沙路125号金沙大厦
搅拌机两相电机四根线怎么在道顺开关上接。
这只活泼可爱的小浣熊是由两句四字成语组成的
精致用阿拉伯语怎么说
能装相片的项链,叫什么名字?
土地坡度对滴灌有影响吗
想知道: 宁波市 余姚高清摄像头地点 在哪
能与箱鼓协奏的乐器有什么
在探究“浮力的大小与什么因素有关”的实验中
下列离子方程式书写正确的是A.铝粉投入氢氧化
js代码,为什么我用了很多clearlnterval还是
本文在塑造钱伟长的形象时主要应用了什么描写
正方形一边上任一点到这个正方形两条对角线的
阴历怎么看 ?