工具: Vs2022
创建一个C++的dll工程
在项目中添加类
.h代码
#pragma once
#include <string>
public ref class dlldemo
{
public:
static int Add(int a, int b);
};
.cpp代码
#include "dlldemo.h"
int dlldemo::Add(int a, int b)
{
return a + b;
}
生成解决方案后,在Debug文件夹就能找到生成的dll文件了。
新建C#工程后,添加引用dll文件 引用 → 添加引用 → 浏览
C#中调用代码
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;
namespace mySoem
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int c = dlldemo.menberFuncAdd(3, 5);
}
}
}
中间编译可能会出错,注意dll和C#中CPU类型配置要一致,32位就都选X86,64位就都选X64;
C++ 常规设置中,公共语言运行时要选择支持;
C++语言设置中,OpenMP支持选是 (/openmp),符合模式选否 (/permissive);
以上就是所有测试过程。