VS2017中C++打包DLL库在CSharp(C#)中调用
程序员文章站
2022-07-14 09:38:08
...
1、新建【具有导出项的(DLL)动态链接库】项目,Dlltest
2、更改配置,改为与C#工程的配置一致,这里改为x64
3、 打开Dlltest.cpp,里面给出了外部接口的示例
仿照给出的例子,我们添加一个测试函数, addtest(int a, int b);
// Dlltest.cpp : 定义 DLL 的导出函数。
//
#include "pch.h"
#include "framework.h"
#include "Dlltest.h"
// 这是导出变量的一个示例
DLLTEST_API int nDlltest=0;
// 这是导出函数的一个示例。
DLLTEST_API int fnDlltest(void)
{
return 0;
}
// 这是已导出类的构造函数。
CDlltest::CDlltest()
{
return;
}
// 测试函数
DLLTEST_API int addtest(int a, int b)
{
return a + b;
}
4、打开Dlltest.h定义函数接口
5、新建模块定义文件.def
新建.def文件的作用就是将接口函数共享出来,这样CSharp才能够找到我们定义的函数接口。
(1)
(2)
(3)打开Source.def输入要共享的函数
6、编译生成DLL文件
7、新建WinForm工程,使用如下代码完成调用
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
[DllImport(@"E:\Codes\VisualStudio\C++\Dlltest\x64\Debug\DLLTEST.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "addtest")]
extern static int addtest(int a, int b);
int test=addtest(1,2);
public Form1()
{
InitializeComponent();
}
}
}
插入断点,test的输出为3。
上一篇: VS2017创建动态库