zoukankan      html  css  js  c++  java
  • 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;
    
    }
    

      

  • 相关阅读:
    Android系统介绍与框架(转)
    6个值得推荐的Android开源框架简介(转)
    程序员最喜爱的12个Android应用开发框架二(转)
    android在代码中四种设置控件(以及TextView的文字颜色)背景颜色的方法
    Android数据缓存(转)
    [UI]实用案例--Shape绘制实用圆圈
    接口API测试和返回值JSON解析的插件
    Android LayoutInflater详解(转)
    一个json字符串
    Android中设定EditText的输入长度(转)
  • 原文地址:https://www.cnblogs.com/alexYuin/p/11928200.html
Copyright © 2011-2022 走看看