在本篇文章中小编给读者们整理了关于C#调用C++dll方法和步骤,需要的朋友们跟着操作下。
C#调用C++dll的方法和步骤
其他分享涉及到的概念和方法对于像我这样比较菜的选手看起来比较费劲并且很难抓住重点,这里我总结了一段时间的研究成果供初学者救济之用,简单明了。
1、新建项目->Visual C++->Win32项目 MyDLL
注意:C++编写的dll一般是不能直接拿来C#调用,需要先新建个C++的工程把dll里的方法重新封装成可被C#外部调用的函数。
2、MyDLL.cpp里的代码如下:
extern "C" _declspec(dllexport)int add(int a ,int b)
{
int sum=a+b;
return sum;
}
注意:函数前一定要加extern "C" _declspec(dllexport),可被外部引用
3、项目->属性->常规->公共语言运行库支持->公共语言运行库支持(/clr)
4、F5编译程序,在Debug文件夹中找到生成MyDLL.dll目标文件备用
1、方法/步骤2
新建项目->Visual C#->控制台应用程序 dllConsoleApplication1
2、将步骤1生成的MyDLL.dll文件copy到dllConsoleApplication1工程的根目录下
3、
Program.cs代码如下using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Runtime.InteropServices; //必须添加,不然DllImport报错namespace dllConsoleApplication1{ class CPPDLL { [DllImport("MyDLL.dll", CharSet = CharSet.Ansi)] //引入dll,并设置字符集 public static extern inProgram.cs代码如下using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Runtime.InteropServices; //必须添加,不然DllImport报错namespace dllConsoleApplication1{ class CPPDLL { [DllImport("MyDLL.dll", CharSet = CharSet.Ansi)] //引入dll,并设置字符集 public static extern int add(int a ,int b); } class Program { static void Main(string[] args) {
t add(int a ,int b); } class Program { static void Main(string[] args) { int sum=CPPDLL.add(3, 4); } }}
int sum=CPPDLL.add(3, 4); } }}
4、
编译程序,在程序中加断点,查看函数的计算结果
5、到这里,C++dll里的方法已经在C#里调用成功了。到这里,C++dll里的方法已经在C#里调用成功了。
本文标题为:C#调用C++dll方法步骤


基础教程推荐
- 实例详解C#实现http不同方法的请求 2022-12-26
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- C#中 Json 序列化去掉null值的方法 2022-11-18
- Unity shader实现高斯模糊效果 2023-01-16
- C# 解析XML和反序列化的示例 2023-04-14
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- C#中的Linq to JSON操作详解 2023-06-08