.Net C# 与 非托管C++互操作性

本文详细介绍了如何配置C++DLL与.NET项目的互操作性调试环境,包括DLL文件输出路径设置、项目属性配置及.NETWinform项目调试选项。同时,提供了互操作性事件处理的具体代码实例,演示了C++DLL如何通过委托调用C#中的事件处理函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

image

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

image

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

image

调试如下图

3333


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

1.1   C++ DLL代码如下:

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

#include "stdafx.h"
typedef void(*Action)();
typedef void (__stdcall *LPFUN)(int);   
_declspec(dllexport) int add(int a, int b, )
{
	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);  
    [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.youkuaiyun.com/yanlinembed/article/details/78920276

转载于:https://www.cnblogs.com/lihuali/p/10539152.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值