C#调用C++ DLL方法之P/Invoke

关于P/Invoke

Platform Invoke (P/Invoke) 是 .NET 提供的一种服务,允许托管代码(如 C#)调用非托管代码(如 C/C++ 编写的 DLL 函数)。通过 P/Invoke,可以在 .NET 应用程序中使用现有的非托管代码库,而无需重写这些库的功能。

P/Invoke 的主要用途包括:

  1. 调用操作系统 API 函数。
  2. 使用现有的非托管库(如 C/C++ 编写的库)。
  3. 与硬件设备进行交互。

使用 P/Invoke 的步骤如下:

  1. 引入 System.Runtime.InteropServices 命名空间。
  2. 使用 DllImport 属性声明非托管函数。
  3. 调用声明的非托管函数。

参考文献
Platform Invoke (P/Invoke)

代码示例

C++部分

复制代码
#include "pch.h"
#include <iostream>

#ifdef __cplusplus
extern "C" {
#endif

    // __stdcall 调用约定的加法函数实现
    __declspec(dllexport) int __stdcall Add(int a, int b)
    {
        return a + b;
    }

#ifdef __cplusplus
}
#endif

C#部分

复制代码
 internal class Program
 {
     // 导入 DLL 的加法函数
     [DllImport("TestDll.dll")]
     public static extern int Add(int a, int b);

     static void Main(string[] args)
     {
         Console.WriteLine("Hello World!");
         int a = 10;
         int b = 20;
         int num = Add(a, b);
         Console.WriteLine("num = {0}", num);
         Console.ReadKey();
     }
 }

记得将C++编译好的dll放入C#启动exe目录下

运行结果

相关推荐
不想写代码的星星12 小时前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
樱木Plus2 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
晨星shine3 天前
GC、Dispose、Unmanaged Resource 和 Managed Resource
后端·c#
用户298698530143 天前
.NET 文档自动化:Spire.Doc 设置奇偶页页眉/页脚的最佳实践
后端·c#·.net
用户3667462526743 天前
接口文档汇总 - 2.设备状态管理
c#
用户3667462526744 天前
接口文档汇总 - 3.PLC通信管理
c#
blasit4 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
Ray Liang4 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
肆忆_5 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星5 天前
虚函数表:C++ 多态背后的那个男人
c++