在C#中如何调用C++编写的DLL

本文介绍两种从C#调用C++编写的DLL的方法:一是通过COM组件;二是通过API方式,利用DllImport导入C++的C接口函数,并提供了一个具体的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有两种办法在C#中调用C++写的DLL的方法有两种:

1、COM

将C++代码封装成COM,然后在C#中引用

 

2、API

将C++代码封装成C接口的函数,类似于Windows的API,然后在C#中通过DllImport引用

 

例如:

c++头文件为

int _stdcall Decrypt(unsignec char *src, unsigned long src_len, unsigned char **dst, unsigned long *dst_len);

 

注:在*.def文件中需呀为定义Decrypt的导出

 

在c#中引用如下命名空章

using System.Runtime.InteropServices;

 

在某个类的构造函数后面添加:

[DllImport("CryptTools.dll")]

internal static extern int Decrypt(System.IntPtr src, int src_len, ref System.IntPtr dst, ref int dst_len);

 

添加函数封装对该API的调用:

internal static int Sharp_Decrypt(byte[] src, ref byte[] dst)

{

int result = -1, dstLen = 0;

 

IntPtr pSrc = Marshal.AllocHGlobal(src.Length);

Marshal.Copy(src, 0, pSrc, src.Length);

 

IntPtr pDst = IntPtr.Zero;

result = Decypt(pSrc, src.Length, ref pDst, ref dstLen);

 

if (0 == result)

{

dst = new byte[dstLen];

Marshal.Copy(pDst, dst, 0, dstLen);

}

 

Marshal.FreeHGlobal(pSrc);

 

return result;

}

 

请注意,出于篇幅的考虑,此处没有在CryptTools.dll中添加unsigned char**的释放函数,需要读者自行添加。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值