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目录下

运行结果

相关推荐
·present·14 小时前
CSAPP(lecture 4_01)
c语言·c++
zimoyin14 小时前
在 C# 里嵌入 JavaScript:用 Jint 做可热更新的自动化脚本(从入门到踩坑)
javascript·c#·自动化
FPGA小迷弟14 小时前
用 Claude Code 重构遗留系统:从评估到落地的完整实践指南
c++·python·ai·plotly·django·ai编程·claude
程序员-King.15 小时前
【ROS1】Noetic 开发工作流程与常用命令
c++·ubuntu·ros
云深麋鹿15 小时前
C++ | 基于红黑树实现mymap与myset
开发语言·c++
傲世仙尊17 小时前
string增删查改-insert-erase-replace与find加substr组合技
c++
小羊没烦恼!17 小时前
异步编程:线程概述及使用
java·开发语言·mysql·算法·c#
·present·18 小时前
CSAPP(lecture 3)
c++
别动我齐刘海18 小时前
机器人 C++ / 系统联调补强2——异常处理、Protobuf
linux·c++·人工智能·学习·算法·机器学习·机器人
c#上位机19 小时前
C#上位机项目实战——exe项目调试更改dll中源代码
开发语言·c#