如何在 C++ 中使用 MethodInvoker?
我有一个 C++/CLI 应用程序,它有一个后台线程。我经常希望它把结果发布到主 GUI 上。我已阅读其他地方 MethodInvoker 可以解决这个问题,但我正在努力将语法从 C# 转换为 C++:
void UpdateProcessorTemperatures(array<float>^ temperatures)
{
MethodInvoker^ action = delegate
{
const int numOfTemps = temperatures->Length;
if( numOfTemps > 0 ) { m_txtProcessor2Temperature->Text = temperatures[0]; } else { m_txtProcessor2Temperature->Text = "N/A"; }
if( numOfTemps > 1 ) { m_txtProcessor2Temperature->Text = temperatures[1]; } else { m_txtProcessor2Temperature->Text = "N/A"; }
if( numOfTemps > 2 ) { m_txtProcessor2Temperature->Text = temperatures[2]; } else { m_txtProcessor2Temperature->Text = "N/A"; }
if( numOfTemps > 3 ) { m_txtProcessor2Temperature->Text = temperatures[3]; } else { m_txtProcessor2Temperature->Text = "N/A"; }
}
this->BeginInvoke(action);
}
...给我:
1>c:\projects\MyTemperatureReporter\Form1.h(217) : error C2065: 'delegate' : undeclared identifier
1>c:\projects\MyTemperatureReporter\Form1.h(217) : error C2143: syntax error : missing ';' before '{'
我在这里缺少什么?
I've got a C++/CLI application which has a background thread. Every so often I'd like it to post it's results to the main GUI. I've read elsewhere on SO that MethodInvoker could work for this, but I'm struggling to convert the syntax from C# to C++:
void UpdateProcessorTemperatures(array<float>^ temperatures)
{
MethodInvoker^ action = delegate
{
const int numOfTemps = temperatures->Length;
if( numOfTemps > 0 ) { m_txtProcessor2Temperature->Text = temperatures[0]; } else { m_txtProcessor2Temperature->Text = "N/A"; }
if( numOfTemps > 1 ) { m_txtProcessor2Temperature->Text = temperatures[1]; } else { m_txtProcessor2Temperature->Text = "N/A"; }
if( numOfTemps > 2 ) { m_txtProcessor2Temperature->Text = temperatures[2]; } else { m_txtProcessor2Temperature->Text = "N/A"; }
if( numOfTemps > 3 ) { m_txtProcessor2Temperature->Text = temperatures[3]; } else { m_txtProcessor2Temperature->Text = "N/A"; }
}
this->BeginInvoke(action);
}
...gives me:
1>c:\projects\MyTemperatureReporter\Form1.h(217) : error C2065: 'delegate' : undeclared identifier
1>c:\projects\MyTemperatureReporter\Form1.h(217) : error C2143: syntax error : missing ';' before '{'
What am I missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
C++/CLI 不支持匿名委托,这是 C# 独有的功能。您需要在类的单独方法中编写委托目标方法。您还需要声明委托类型,MethodInvoker 无法完成这项工作。让它看起来像这样:
C++/CLI doesn't support anonymous delegates, that's an exclusive C# feature. You need to write the delegate target method in a separate method of the class. You'll also need to declare the delegate type, MethodInvoker can't do the job. Make it look like this: