最近公司需要将一个C++多线程实例封装成DLL供C#程序使用,首先学习一波C++封装DLL。
学习环境:vs2019
一、创建动态链接库项目
项目最终创建结果(高亮部分 myDll.h\myDll.cpp)为后来人为创建文件,内容见下文,其余文件为程序自动生成的。
myDLL.h
#ifndef _ENCRYPTBASE_H //定义_ENRYPTBASE_H宏,是为了防止头文件的重复引用
#define _ENCRYPTBASE_H
#ifdef __cplusplus //而这一部分就是告诉编译器,如果定义了__cplusplus(即如果是cpp文件,
extern "C" { //因为cpp文件默认定义了该宏),则采用C语言方式进行编译
#endif
#ifdef DLL_EXPORTS
#define DLL_EXPORTS __declspec(dllexport)
#else
#define DLL_EXPORTS __declspec(dllimport)
#endif
DLL_EXPORTS int Sum(int value1, int value2);
#ifdef __cplusplus
}
#endif
#endif // !_ENCRYPTBASE_H
myDLL.cpp
// EncryptBase.cpp: 定义 DLL 应用程序的导出函数。
//
//
#include "pch.h"
#include "myDll.h"
#include "framework.h"
int Sum(int value1, int value2)
{
int sumValue = value1 + value2;
return sumValue;
}
复制粘贴即可使用,但还有部分注意事项请看下文。
选中myDll项目右键选择属性打开下列窗口,将各属性设置为如图高亮部分点击应用。
设置完成后再次选择myDLL项目,右键生成,生成的结果如图:该文件在路径为D:\myProject\C++Project\myDLL\myDll\x64\Debug 该路径为项目路径你的可能会与我不同。
将生成的myDll.dll文件复制,注意:后面有用到记得这个文件位置:
二、创建c#测试小案例
创建C#窗体应用程序
创建成功后拖入一个button控件,效果如下图:
运行程序,使其生成debug文件,最终生成的文件路径为:D:\MyProject\myProject\C#Project\DllDemo\bin\x64\Debug
将上方复制的myDll.dll文件复制到当前文件夹内,结果如下图:
返回项目双击button控件输入下方代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DllDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//在c#中调用c++ dll库
[DllImport("myDll.dll")]
static extern int Sum(int value1, int value2);
private void button1_Click(object sender, EventArgs e)
{
int result = Sum(1, 4);
MessageBox.Show(result.ToString());
}
}
}
注意事项:c#小案例需要设置64位环境下运行
最终运行结果如下: