宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取

(一).Net互操性调试环境配置

1.1  将C++ DLL文件输出到主EXE所在目录

.Net C# 与 非托管C++互操作性-冯金伟博客园

1.2  配置C++ DLL项目属性的命令调试器类型两项

.Net C# 与 非托管C++互操作性-冯金伟博客园

1.3   配置.NET Winform项目属性调试选项。一定要选择“启用本地代码调试”

.Net C# 与 非托管C++互操作性-冯金伟博客园

调试如下图

.Net C# 与 非托管C++互操作性-冯金伟博客园

(二)互操作性的事件处理

1.1   C++ DLL代码如下:

代码// Bsr.Hardware.cpp : 定义 DLL 应用程序的导出函数。
//

#include "stdafx.h"
typedef void(*Action)();
typedef void (__stdcall *LPFUN)(int);   //定义一个函数指针,此处必须要定义一个函数指针,如果定义为add(int a,int b,void(*ball)(int))这种方式,则C#回调时将无法返回到C++ DLL中的函数调用。
_declspec(dllexport) int add(int a, int b, LPFUN ball=nullptr)
{
	int ret = a + b;
	if (ball != nullptr) {
		ball(ret);
	}
	
	return ret+100;
}

_declspec(dllexport) int add1(int a, int b)
{
	int ret = a + b;

	return ret;
}

1.2   C#调用代码

代码public partial class Form1 : Form
{
    public delegate void AddEvent(int x);  //定义委托来与DLL中函数指针匹配
    [DllImport("Bsr.Hardware.DLL", EntryPoint = "add", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
    public static extern int add(int a, int b, AddEvent act);
    [DllImport("Bsr.Hardware.DLL", EntryPoint = "add1", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
    public static extern int add1(int a, int b);
   
    public static void ActEvent(int x)
    {
        MessageBox.Show(x.ToString());

    }

    private void button1_Click(object sender, EventArgs e)
    {
        AddEvent ev = new AddEvent(ActEvent);
        int ret = add(100, 100, ev);
        int y = 100;
        MessageBox.Show("f1=" + ret.ToString());
    }
}

https://blog.csdn.net/yanlinembed/article/details/78920276