C++定義函式指標,回撥C#

!>Mon<!發表於2024-07-02

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;
        }
    }
}

實現效果

相關文章