c++动态库打包为dll文件供C#项目调用
C++与C#接口交互需要通过DLL库来完成。
编写C++动态库
创建项目:
添加C++测试类:
在MathAPI.h定义接口方法:
#pragma once
class MathAPI
{
public:
MathAPI();
~MathAPI();
static _declspec(dllexport) double Add(double a, double b);
static _declspec(dllexport) double Subtract(double a, double b);
static _declspec(dllexport) double Multiply(double a, double b);
static _declspec(dllexport) double Devide(double a, double b);
};
在MathAPI.cpp实现接口方法:
#include "pch.h"
#include "MathAPI.h"
#include "stdexcept"
MathAPI::MathAPI()
{
}
MathAPI::~MathAPI()
{
}
double MathAPI::Add(double a, double b)
{
return a + b;
}
double MathAPI::Subtract(double a, double b)
{
return a - b;
}
double MathAPI::Multiply(double a, double b)
{
return a * b;
}
double MathAPI::Devide(double a, double b)
{
if (b == 0)
{
throw new _exception;
}
return a / b;
}
修改项目的属性,输出为动态库dll:
然后生成即可。
C#调用dll库
利用vs提供的dumpbin.exe工具可以查看dll的入口,在vs安装目录搜索即可找到。
dumpbin的选项指令:
为了快速看到效果,直接将FFmpegDXVA2dll.dll文件复制到dumpbin.exe所在的目录执行以下命令 :
上面输出中?Add@MathAPI@@SANNN@Z 表示ADD函数的入口,我们在C#程序中使用时需要设置这个入口。
创建一个C#控制台程序,并将我们需要的dll库放入其中:
C#中定义dll接口访问:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace DllImportTest
{
public class Math
{
[DllImport("FFmpegDXVA2dll.dll", EntryPoint = "?Add@MathAPI@@SANNN@Z", CallingConvention = CallingConvention.Cdecl)]
public static extern double Add(double a, double b);
[DllImport("FFmpegDXVA2dll.dll", EntryPoint = "?Subtract@MathAPI@@SANNN@Z", CallingConvention = CallingConvention.Cdecl)]
public static extern double Subtract(double a, double b);
[DllImport("FFmpegDXVA2dll.dll", EntryPoint = "?Multiply@MathAPI@@SANNN@Z", CallingConvention = CallingConvention.Cdecl)]
public static extern double Multiply(double a, double b);
[DllImport("FFmpegDXVA2dll.dll", EntryPoint = "?Devide@MathAPI@@SANNN@Z", CallingConvention = CallingConvention.Cdecl)]
public static extern double Devide(double a, double b);
}
}
Program运行:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DllImportTest
{
class Program
{
static void Main(string[] args)
{
double a = 20, b = 5;
Console.WriteLine(Math.Add(a,b));
Console.WriteLine(Math.Subtract(a, b));
Console.WriteLine(Math.Multiply(a, b));
Console.WriteLine(Math.Devide(a, b));
Console.Read();
}
}
}
输出结果:
至此,C#已经成功实现调用C++ 动态dll库的功能了。
参考文章:
纸上得来终觉浅,绝知此事要躬行。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
2014-09-15 JOSM学习下载地址
2014-09-15 [转]JSOM绘制地图区块及航道路径