博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#调用C++ dll,C++返回类型为char*,并通过指针传出值
阅读量:3906 次
发布时间:2019-05-23

本文共 1986 字,大约阅读时间需要 6 分钟。

C#调用C++ dll,C++返回类型为char*,并通过指针传出值

编写生成c++ dll

  1. 在项目属性页修改项目类型为动态库(.dll)
    在这里插入图片描述
  2. 编写头文件,声明要导出的函数
    编写一个动态链接库,需要在一个头文件.h中声明你要导出的函数,并在对应的.cpp中实现需要导出的函数。同时也需要定义导出符号,注意导出符号的前缀应保持与项目名一致:
    在这里插入图片描述
    在.cpp文件中,include编写好的对应头文件:
    在这里插入图片描述
  3. 生成解决方案,在工程目录下找到生成的dll,具体位置可以通过属性页->链接器->常规->输出文件查看:在这里插入图片描述

Unity C#中调用C++ dll

  1. 将生成的.dll文件,放在Unity工程的Assets/Plugins文件夹下:
    在这里插入图片描述
  2. 在C#脚本中导入需要调用的dll接口函数,如下图:
    在这里插入图片描述
    通过以上两步就可以在此脚本中调用这些函数了。

C#调用C++ dll,返回值为char*,并通过指针修改传出值

编写C++程序,生成dll库:

// CDLLDemo.cpp : 定义 DLL 应用程序的导出函数。//#include "stdafx.h"#include "string.h"#include 
#include
char * ParseBaliseMsg(const unsigned char *pMsgData, char *resTgm, int & retInt){
printf("%s \r\n", pMsgData); char *resStr = "ParseBaliseMsg hello word!"; printf("resStr is: %s \r\n", resStr); time_t rawtime; struct tm * timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); printf("The current date/time is: %s \r\n", asctime(timeinfo)); retInt = 130; return resStr;}

C#中调用C++ dll:

using System;using System.Collections.Generic;using System.Linq;using System.Runtime.InteropServices;using System.Text;using System.Threading.Tasks;namespace DotNet_Use_C_Demo{
public class TestCMethodHelper {
[DllImport("CDLLDemo.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)] private static extern IntPtr ParseBaliseMsg3(string msg, string rmsg, ref int rInt); } public static void TestMethod() {
int retResult = 0; IntPtr pRet = ParseBaliseMsg3("1234", "", ref retResult); string strRet = Marshal.PtrToStringAnsi(pRet); Console.WriteLine("返回值:" + strRet); Console.WriteLine("传出值:" + retResult); Console.WriteLine("***************************************************"); }}

运行输出如下:

resStr is: ParseBaliseMsg hello word!The current date/time is: Tue Nov 13 10:29:30 2020返回值: ParseBaliseMsg hello word!传出值: 130***************************************************

:如果想将返回的IntPtr存入byte[]中,可以通过Marshal.Copy的方法:

在这里插入图片描述

参考资料

C++编写dll:

C#调用C++ dll:

转载地址:http://floen.baihongyu.com/

你可能感兴趣的文章
linux PCIe hotplug arch analysis
查看>>
LDD3 study note 0
查看>>
PCI SMMU parse in ACPI
查看>>
345. 反转字符串中的元音字母
查看>>
67. 二进制求和
查看>>
125. 验证回文串
查看>>
168. Excel表列名称
查看>>
400. 第N个数字
查看>>
209. 长度最小的子数组
查看>>
145. 二叉树的后序遍历
查看>>
2. 两数相加
查看>>
3. 无重复字符的最长子串
查看>>
5. 最长回文子串
查看>>
4. 两个排序数组的中位数
查看>>
23. 合并K个元素的有序链表
查看>>
6. Z字形转换
查看>>
8. 字符串转整数(atoi)
查看>>
15. 三数之和
查看>>
16. 最接近的三数之和
查看>>
18. 四数之和
查看>>