1.创建c++动态连接库
c++头文件如下:
#pragma once
#ifdef Calc_EXPORTS
#define Calc_API __declspec(dllexport)
#else
#define Calc_API __declspec(dllimport)
#endif
extern "C" Calc_API int AddNum();
c++cpp文件如下:
#include "Calc.h"
#include "pch.h"
int AddNum()
{
return 123;
}
2.c#调用
将dll放在对应的debug下
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ExeWinForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("ExeCppDll.dll", EntryPoint = "AddNum", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
public static extern int AddNum();
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Console.WriteLine("=====" + AddNum());
}
}
}
3.结果
4.微软教程如下: