C#调用C++编写的DLL整型和字符串传参

C#调用C++编写的DLL整型和字符串传参

直接返回值

DLL返回字符串

C++ Code:

extern "C" __declspec(dllexport) char* GetStr()

{
        string s = "This is a string";
       return _strdup(s.c_str());   //一定要用_strdup()复制一段内存,不然等调用结束字符串内存会被释放得到一串乱码

}

C# Code:

public class CppDll
{
        [DllImport(DllPath, CallingConvention = CallingConvention.Cdecl)]
        public extern static IntPtr GetStr();
        
        public static GetStrFun()
        {
                IntPtr p = GetStr();    //调用DLL函数
                string s = Marshal.PtrToStringAnsi(p);   //根据实际情况决定使用PtrToStringUni还是PtrToStringAnsi
        }

}

DLL返回整型

C++ Code:

extern "C" __declspec(dllexport) int GetInt()

{
       return 1;
}

C# Code:

public class CppDll
{
        [DllImport(DllPath, CallingConvention = CallingConvention.Cdecl)]
        public extern static int GetInt();
}

int res = CppDll.GetInt();  //调用

参数传参

除了可以在返回值里带出字符串,也可以在函数参数中带出,类似与C语言中需要获取多个值的情形,这里展示一下DLL中同时传递字符串和整型量。由于C#为托管内存,C++运行在非托管内存,所以需要在C#中手动申请一块内存用来存储C++中返回的值。

C# Code:

public CppDll
{
        [DllImport(DllPath, CallingConvention = CallingConvention.Cdecl)]
        public extern static int GetCapInfo(int index, IntPtr proName, IntPtr cnt);
}

IntPtr PproName = Marshal.AllocHGlobal(256);    //手动申请存储字符串类型
IntPtr Pcnt = Marshal.AllocHGlobal(sizeof(int));    //存储整数类型

int status = CppDll.GetCapInfo(0, PproName, Pcnt);

string proName = Marshal.PtrToStringAnsi(PproName);
int cnt = Marshal.ReadInt32(Pcnt);

Marshal.FreeHGobal(PproName);   //手动申请的内存手动释放
Marshal.FreeHGobal(Pcnt);


C++ Code:

extern "C" __declspec(dllexport) int GetCapInfo(int index, char* proName, int* cnt) //后两个参数为需要传递的值
{
       if (index >= capHlp.pro_to_cnt.size())
       {
              return -1;
       }
       string key = capHlp.proIndex[index];
       *cnt = capHlp.pro_to_cnt[key];           // 把需要传递的整数复制到指定内存
       sprintf_s(proName, 256, key.c_str());    //把需要传递的字符串复制到指定内存
       return 0;
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值