使用VS2019创建一个简单的dll并在C# 中调用它,在此记录一下使用过程。
一 创建dll
创建一个windows C++ 库

项目名称是add

添加add.h 和 add.cpp文件
在头文件处,鼠标右键,弹出菜单选择【添加】-》【类】

填写类名【add】,点击确定,会自动添加了add.h 和 add.cpp文件


DllMain函数 是dll的入口函数,具体介绍可参考百度百科的介绍:https://baike.baidu.com/item/DllMain?fromModule=lemma_inlink

add.h头文件,删除自动生成的类,我们写简单的加减乘除函数。


add.h 代码如下
#pragma once
#ifndef _ADD_H
#define _ADD_H
extern "C" _declspec(dllexport) long DemoAdd(long a, long b);
extern "C" _declspec(dllexport) long DemoSub(long a, long b);
extern "C" _declspec(dllexport) long DemoMul(long a, long b);
extern "C" _declspec(dllexport) long DemoDiv(long a, long b);
#endif
add.cpp 如下,写函数的实现

add.cpp具体代码如下:
#include "pch.h"
#include "add.h"
long DemoAdd(long a, long b)
{
return a + b;
}
long DemoSub(long a, long b)
{
return a - b;
}
long DemoMul(long a, long b)
{
return a * b;
}
long DemoDiv(long a, long b)
{
return a / b;
}
设置项目的属性
鼠标右键【add】项目,选择【属性】。在【配置属性------> C/C+±------>预编译头】,选择【不使用预编译头】

生成dll
鼠标右击项目【add】,选择【生成】,在项目目录下可以看到dll已经生成了

二 调用dll
在这里,新一个windform的工程,来测试一下调用add.dll中的函数。
创建测试工程


工程创建完毕后,运行一下。将前面生成的add.dll复制到测试工程的exe运行程序目录下

简单设计一下布局

具体代码如下:
DllImport 的命名空间using System.Runtime.InteropServices
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace testAdd
{
public partial class Form1 : Form
{
//dll名称 //dll中入口点的名称 //入口点的调用约定
[DllImport("add.dll", EntryPoint = "DemoAdd", CallingConvention = CallingConvention.Cdecl)]
//CallingConvention = CallingConvention.Cdecl 意味着参数可变长
public static extern int Add(int lA, int lB);
[DllImport("add.dll", EntryPoint = "DemoSub", CallingConvention = CallingConvention.Cdecl)]
public static extern int Sub(int lA, int lB);
[DllImport("add.dll", EntryPoint = "DemoMul", CallingConvention = CallingConvention.Cdecl)]
public static extern int Mul(int lA, int lB);
[DllImport("add.dll", EntryPoint = "DemoDiv", CallingConvention = CallingConvention.Cdecl)]
public static extern int Div(int lA, int lB);
public Form1()
{
InitializeComponent();
}
private void BtnCalculate_Click(object sender, EventArgs e)
{
int a = (int)numericUpDown1.Value;
int b = (int)numericUpDown2.Value;
int c = Add(a, b);
textBox1.Text = c.ToString();
textBox2.Text = Sub(a, b).ToString();
textBox3.Text = Mul(a, b).ToString();
textBox4.Text = Div(a, b).ToString();
}
}
}
运行结果如下:

注意:
调用的dll生成的是x86还是x64的,被调用者testAdd也需要注意一下运行的平台是否一致哈。
3413




被折叠的 条评论
为什么被折叠?



