我正在使用 Windows winform,并且我有另一个带有 Detector.h 和 Detector.cpp 文件的 ref 类检测器。
在 Detector.cpp 文件的成员函数中,我想创建一个可以更新图片框图像的线程。
void updatethread(Detector ^obj, const char* frame) {
updateDisplay(frame);
}
void Detector::updateDisplay(frame){
//convert frame to bitmap
Picturebox-> image = bmp;
}
int Detector::Listener(XcAPI& det, const API_SETTINGS& api, const DETECTOR_INFO& info){
//some code
auto th = std::thread(updatethread, std::cref(this));// my focus is here how can i do it
}
我尝试过 Lamda,但它说我们不能使用 lamda 函数
由于 C++11 lambda 语法和 .NET 委托之间没有集成,捕获参数有点痛苦。
不带参数(目标对象除外):
auto th = gcnew System::Threading::Thread(
gcnew System::Threading::ThreadStart(this, &Detector::updateDisplay));
th->Run();
代码中没有任何内容为
frame
参数提供值,因此您必须根据需要填写 closure->frame =
行。
ref struct FrameClosure
{
delegate void Callback(const char* frame);
const char* frame;
Callback^ target;
void Invoke() { target(frame); }
};
auto closure = gcnew FrameClosure();
closure->frame = "Test value";
closure->target = gcnew FrameClosure::Callback(this, &Detector::updateDisplay);
auto th = gcnew System::Threading::Thread(
gcnew System::Threading::ThreadStart(closure, &FrameClosure::Invoke));
th->Run();
如果你用 C# 编写它,编译器会为你做的事情:
var th = new Thread((ThreadStart)delegate { updateDisplay("Test value"); });
th.Run();