本文共 1986 字,大约阅读时间需要 6 分钟。
属性页->链接器->常规->输出文件
查看:编写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/