0x00 引言
再简单的事情,也需要有人去做。
0x01 函数指针
C语言的回调函数主要通过函数指针的方式实现,相关主要代码如下:
typedef void(*CallbackFunc)(int mes_length);
void callback(int mes_length) // 回调函数
{
std::cout << mes_length <<std::endl;
}
extern "C" void __declspec(dllimport) SetReadCallback(CallbackFunc callback) // 调用函数
{
int length = 0;
callback(length);
}
int main(int argc,char* argv[]) // 实现函数回调
{
SetReadCallback(callback);
return 0;
}
0x02 C调用
void callback(int mes_length)
{
std::cout << mes_length <<std::endl;
}
int main()
{
SetReadCallback(callback);
return 0;
}
0x03 C#调用
C#这边主要通过委托(delegate)来实现,具体代码如下:
using System.Runtime.InteropServices;
namespace Test
{
class Program
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void CallbackFunc(int mes_length);
[DllImport(@"test.dll", EntryPoint = "CCasicDDSCtrl2ModelSubscriberSharpSetCallback",
SetLastError = true,CharSet = CharSet.Unicode, ExactSpelling = false,
CallingConvention = CallingConvention.Cdecl)]
extern static bool SetReadCallback(CallbackFunc callback);
static void Main(string[] args)
{
SetReadCallback(Program.CsharpCallback);
}
public static void CsharpCallback(int mes_length)
{
Console.WriteLine(mes_length);
}
}
}
0x04 UPDATE
2019-02-19