代码如下:
#pragma once #include <iostream> //字节对齐 #ifdef __GNUC__ #define SNFTK_PACKED(...) __VA_ARGS__ __attribute__((__packed__)) #elif _MSC_VER #define SNFTK_PACKED(...) __pragma(pack(push, 1)) __VA_ARGS__ __pragma(pack(pop)) #else #error Unknown compiler #endif typedef void(*callbackFunc1) (); typedef void(*callbackFunc2) (float a, float b); typedef void(*callbackFunc3) (int a, float b); SNFTK_PACKED(typedef struct { callbackFunc1 TestFunc1; callbackFunc2 TestFunc2; callbackFunc3 TestFunc3; } callBackFuncs); //将Test3类中的回调函数注入到Test2中 class Test2 { public: static Test2& GetInstance() { static Test2 t; return t; } void init(void* ptr) { cbfs = (callBackFuncs*)ptr; } callBackFuncs* GetCallBackFuncs() { return cbfs; } private: callBackFuncs* cbfs; }; class Test3 { public: void test1() { std::cout << "321" << std::endl; } void test2(float a, float b) { std::cout << "654" << std::endl; } void test3(int a, float b) { std::cout << "987" << std::endl; } void init() { callBackFuncs callBacks = { 0 }; callBacks.TestFunc1 = &(Test3::test1); callBacks.TestFunc2 = &(Test3::test2); callBacks.TestFunc3 = (Test3::test3); Test2 t2 = Test2::GetInstance(); t2.init((void*)(&callBacks)); } }; void demo() { } int main() { while (1); return 0; }