C++定义函数指针,回调C#

C++定义函数指针。

typedef int (__stdcall * delegate_func)(int a, int b);

暴露接口:int __stdcall CPPcallCSharp(delegate_func func);

方法实现:int __stdcall CPPcallCSharp(delegate_func func) { return func(1,2); }

头文件calculator.h

#ifndef LIB_CALCULATOR_H
#define LIB_CALCULATOR_H


typedef int(__stdcall *delegate_func)(int a, int b);

int __stdcall CPPcallCSharp(delegate_func func);

#endif

源文件calculator.h

// calculator.cpp : Defines the exported functions for the DLL application.
//

#include "stdafx.h"
#include "calculator.h"

int __stdcall CPPcallCSharp(delegate_func func) 
{
    return func(1, 2);
}

C#定义委托。

public delegate int delegate_func(int a, int b);

添加方法:public int callBackFunc(int a, int b) { Return a+b; }

C#中实现C++接口:

[DllImport("CppLib.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]

public static extern int CPPcallCSharp(delegate_func func);

C#中调用C++接口,实现回调

public event delegate_func callBack_event =null; callBack_event += new delegate_func(callBackFunc); CPPcallCSharp(callBack_event); 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace csharpCallCpp
{

    public partial class Form1 : Form
    {
        public delegate int delegate_func(int a,int b);

     //导入C++接口
        [DllImport("calculator.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
        public static extern int CPPcallCSharp(delegate_func func);

        public Form1()
        {
            InitializeComponent();
        }

        public  event delegate_func callBack_event =null;
        private void button1_Click(object sender, EventArgs e)
        {
            callBack_event += new delegate_func(callBackFunc);//指定回调方法callBackFunc
            int iret=CPPcallCSharp(callBack_event);//执行该代码时,方法callbackFunc被执行,且返回(1+2)
            MessageBox.Show("function return:" + iret);
        }
        public  int callBackFunc(int a, int b)
        {
            return a+b;
        }
    }
}

实现效果

 

posted @ 2024-07-02 17:18  !>Mon<!  阅读(2)  评论(0编辑  收藏  举报