惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - Franky
N
Netflix TechBlog - Medium
宝玉的分享
宝玉的分享
Google DeepMind News
Google DeepMind News
腾讯CDC
G
Google Developers Blog
Martin Fowler
Martin Fowler
Microsoft Security Blog
Microsoft Security Blog
Recent Announcements
Recent Announcements
爱范儿
爱范儿
Engineering at Meta
Engineering at Meta
Microsoft Azure Blog
Microsoft Azure Blog
A
About on SuperTechFans
aimingoo的专栏
aimingoo的专栏
有赞技术团队
有赞技术团队
Jina AI
Jina AI
人人都是产品经理
人人都是产品经理
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
M
MIT News - Artificial intelligence
罗磊的独立博客
博客园 - 三生石上(FineUI控件)
美团技术团队
WordPress大学
WordPress大学
阮一峰的网络日志
阮一峰的网络日志

博客园 - wu.g.q

旧电脑适合的系统 安川机器人遇见的问题汇总 Estun机器人数据断电保持问题解决方案 安川机器人快捷键 安川机器人变量代替常量的转换关系 创建自己的代码仓库 vc6.0 txt文件资源转为xaml资源 查看Windows操作系统编码方式 wpf 元素设置焦点无效的问题 汽车知识总结 wpf - 设置滚动条拇指(Thumb)大小 C# 反序列化乱码 C# 确定文件编码格式的方法 C# 反序列化报错 XML 文档(1, 2)中有错误:不应有 <xml xmlns=''> xsd.exe语法示例 C# 获取XML文件内容的多种方式 VC6.0 dll debug C#与C++动态链接库DLL参数互传 C#调用C/C++动态库dll异常:对 PInvoke 函数调用导致堆栈不对称问题
C#动态调用C/C++的DLL
wu.g.q · 2023-07-28 · via 博客园 - wu.g.q

C#调用C/C++的dll有两种方式,下边就写一下两种不同方式的调用方法。

1.DllImport方式
[DllImport("CalcDll")]
public extern int Add(int a, int b);
其中CalcDll为C++动态库,Add为动态库中的方法,使用DllImport引入需要加载的DLL,使用关键字extern修饰C++库中的方法,之后正常调用即可。

2.动态加载
1.首先引入以下三个方法

[DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr LoadLibrary(string lpFileName, int h, int flags);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lProcName);
[DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall)]
private static extern bool FreeLibrary(IntPtr hModule);
2.加载DLL

IntPtr m_hModule = LoadLibrary(@"D:\CalcDll.dll", 0, (int)LoaderOptimization.MultiDomain);
其中dll路径必须是全路径。

3.定义方法的委托

private delegate int Delegate_Add(int x,int y);
private Delegate_Add m_Delegate_Add;
4.动态获取该函数的委托方法对象

IntPtr func = GetProcAddress(m_hModule, “Add”);
Type t=typeof(Delegate_Add);
m_Delegate_Add=(Delegate)Marshal.GetDelegateForFunctionPointer(func, t);
其中“Add”为C++动态库中的函数名。

5.调用委托方法

int sum=m_Delegate_Add(2,3);
注意使用完之后加入析构函数,一定要释放m_hModule

~CDriver() { FreeLibrary(m_hModule); }

原文链接:https://blog.csdn.net/jh_negit/article/details/117446570