【问题标题】:How to use boost to run thread another object function with callback如何使用 boost 运行线程另一个带有回调的对象函数
【发布时间】:2013-04-08 12:59:28
【问题描述】:

我试图通过回调运行 boost::thread 一些对象函数

在A类中有这样一个函数:

void DoWork(int (*callback)(float))   
{
float variable = 0.0f;

 boost::this_thread::sleep(boost::posix_time::seconds(1));
int result = f(variable);
}

在主要:

int SomeCallback(float variable)
{
  int result;
  cout<<"Callback called"<<endl;
  //Interpret variable

  return result;
}



int main(){
  A* file = new A();

boost::thread bt(&A::DoWork, file , &SomeCallback );
cout<<"Asyns func called"<<endl;
bt.join();
cout<<"main done"<<endl; 
}

boost::thread bt(&amp;A::DoWork, file , &amp;SomeCallback ); 行导致 链接器 错误。我从本教程中接听的电话: http://antonym.org/2009/05/threading-with-boost---part-i-creating-threads.html.

错误是:

unresolved external symbol "public: void __thiscall A::DoWork(int (__cdecl*)(float))" (?DoWork@A@@QAEXP6AHM@Z@Z) referenced in function _main

这段代码有什么问题?

【问题讨论】:

  • callback 曾经在 DoWork 中使用过吗?
  • 您可能对 boost.asio 感兴趣,以满足您的异步需求。
  • @DrewDormann 我猜这是一个拼写错误/复制错误 - fcallback 很可能是相同的。
  • 是的,再次复制出现问题

标签: c++ boost asynchronous


【解决方案1】:

unresolved external symbol是链接器错误,表示链接器找不到A::DoWork的定义。从您的代码中,我看不到您实际定义函数的位置,但让我猜猜:

//A.h

class A {
  //...
public:
  void DoWork(int (*callback)(float)); //declaration
};

//A.cpp

void DoWork(int (*callback)(float))   
{
  float variable = 0.0f;

  boost::this_thread::sleep(boost::posix_time::seconds(1));
  int result = f(variable);
}

如果定义与您在 .cpp 文件中发布的完全相同,则错误是您没有定义 A::DoWork,而是定义了一个新的免费函数。

那么正确的定义应该是:

//A.cpp

void A::DoWork(int (*callback)(float))   //define it as a member of A!
{
  float variable = 0.0f;

  boost::this_thread::sleep(boost::posix_time::seconds(1));
  int result = f(variable);
}

如果我的猜测有误,请提供SSCCE,以便我们评估真正的问题所在。

【讨论】:

  • 不丢人,这种情况经常发生在很多人身上,通常只是将函数签名从标头复制到 cpp 并忘记写 A:: - 这是人们应该首先寻找的东西之一如果有人得到未解决的引用。
  • 是的,在复制过程中。非常感谢。如果我想调用一些 int SomeCallback 方法,而不是在 Main.cpp 中定义被定义为例如 A 类的一部分,该怎么办?这次我确定正确定义了方法并得到编译错误。我正在尝试使用 boost::thread bt(&A::DoWork, file, &A::SomeCallback );
  • 在这种情况下,我会使用 boost::function&lt;int(float)&gt; 而不是函数指针并像 boost::thread bt(&amp;A::DoWork, file, boost::bind(&amp;A::SomeCallback, file)) 一样调用它,或者如果 all 的回调是成员函数,请使用像void A::DoWork(int (A::*callback)(float)) { this-&gt;*callback(0.5f); } 这样的成员函数指针。我更喜欢 C++11 和 std::functionand lambdas 而不是 bind
  • 使用绑定,我看到了对类模板实例化 'boost::_mfi::dm' 的引用正在编译,然后是“错误 PRJ0002:从 'C: 返回错误结果 1: \Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\cl.exe"
  • 嗯。也许这应该进入一个新问题?对我来说似乎充其量只是一个松散相关的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多