c++ 学习之 回调函数2:类中传递回调

22 篇文章 0 订阅

首先声明一个解码类,解码出图像后调用回调

#include <iostream>
#include <string>
#include <cstdlib>
#include <opencv2\opencv.hpp>

#include <Windows.h>
#include <process.h> 

using namespace std;
using namespace cv;

//利用回调函数在解码类中取图像数据
typedef void(*AVFunction)(Mat img);	//定义回调函数类型


class MyCoder
{
public:
	MyCoder(string VideoPath, void(*vfun)(Mat img));
	~MyCoder();

private:

public:
	bool m_bStart;
	string mVideoPath;
	AVFunction mCallFunction;
	static unsigned _stdcall  ThreadFunc(void* param);
};

MyCoder::MyCoder(string VideoPath, void(*vfun)(Mat img))
{
	m_bStart = true;
	mVideoPath = VideoPath;
	mCallFunction = vfun;
	HANDLE handle2 = (HANDLE)_beginthreadex(NULL, 0, ThreadFunc, (void*)this, NULL, NULL);
}

MyCoder::~MyCoder()
{
}

unsigned MyCoder::ThreadFunc(void * param)
{
	MyCoder * helper = (MyCoder*)param;

	VideoCapture vcap(helper->mVideoPath);
	if (!vcap.isOpened())
	{
		return -1;
	}
	while (helper->m_bStart)
	{
		Mat frame;
		vcap >> frame;
		if (frame.empty())
		{
			break;
		}
		helper->mCallFunction(frame);
		waitKey(30);
	}
}

再声明一个显示的类

class MyPlay
{
public:
	MyPlay();
	~MyPlay();

private:

public:
	bool m_bStart;	
	void StartPlay(string VideoPath, int durtion);
	//回调,需设为静态
	static void CallFunction(Mat img);
};

MyPlay::MyPlay()
{
	m_bStart = false;
}

MyPlay::~MyPlay()
{
	m_bStart = false;
}

void MyPlay::CallFunction(Mat img)
{
	//回调取数据显示
	imshow("img", img);
}

void MyPlay::StartPlay(string VideoPath, int durtion)
{
	m_bStart = true;
	MyCoder * mCoder = new MyCoder(VideoPath, CallFunction);
	int count = 0;
	while (count<durtion)
	{
		count += 1;
		Sleep(1000);
	}
	mCoder->m_bStart = false;
	Sleep(1000);
	m_bStart = false;
}

启动解码器, 大笑

int main()
{
	MyPlay * player = new MyPlay();
	player->StartPlay("video.mp4", 10);

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值