
代碼// 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;
}

代碼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());
}
}