C++ 回调函数 Callback 机制例程

#include <iostream>

#include <thread>
#include <mutex>

#include <Windows.h>


// callback test



/////////////////////////////////////////////////////////////

// API part
typedef void(__stdcall *CallbackEvent)(const char* pStr, bool bOK, void * any);


/////////////////////////////////////////////////////////////

// API part
class API
{
public:
	API() = delete;
	API(CallbackEvent pCallBack, const char* pStr, bool bOK, void * any=nullptr)
		:
		mpStr	  (pStr	  )	  ,
		mbOK	  (bOK	  )	  ,
		mpCallBack(pCallBack) ,
		mAny	  (any)
	{
		mThread = std::make_unique<std::thread>(&API::run, this);
		mThread->detach();
	}

	~API(){};

	void run()
	{
		int i = 0;
		while (true)
		{
			Sleep(50);

			if (i % 10 == 0)
			{
				// start callback event
				//auto str = std::to_string(i);
				mpCallBack(mpStr, mbOK, mAny);
			}

			std::cout << "i = " << i << std::endl;
			++i;

			if (i == 200)
			{
				break;
			}

		}
	}
private:
	std::unique_ptr<std::thread> mThread    ;
	CallbackEvent	mpCallBack;

	// parameter of callback function.
	const char*		mpStr		;
	bool			mbOK		;
	void *			mAny		;
};


/////////////////////////////////////////////////////////////

typedef struct passToCallbackFun
{
	passToCallbackFun(int w, int h) 
		: 
		width (w),
		height(h)
	{}
	int width ;
	int height;
} ImgSize;

// user definition
void __stdcall onCallback(const char* pStr, bool ok,  void * any)
{
	std::cout << "doing: " << pStr << ", ok = " << ok << std::endl;

	if (any == nullptr) return;

	ImgSize* iSize = (ImgSize*)any;
	std::cout << "size: w=" << iSize->width << ", h= " << iSize->height << std::endl;
}

/////////////////////////////////////////////////////////////

int main()
{
	// register callback event
	std::string str("adc");
	ImgSize isize(10, 20);
	API api(onCallback, str.c_str(), true, &isize);

	// hold main thread
	int i = 0;
	while (true)
	{
		Sleep(50);

		if (i % 10 == 0)
		{
			// do something
		}

		//std::cout << "i = " << i << std::endl;
		++i;

		if (i == 200)
		{
			break;
		}

	}

	return 0;

}

  

原文链接: https://www.cnblogs.com/alexYuin/p/11928200.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++ 回调函数 Callback 机制例程

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/306413

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月16日 上午4:17
下一篇 2023年2月16日 上午4:19

相关推荐