c++ - 将 boost shared_ptr 转换为 void*,反之亦然

标签 c++ boost

我可以将 boost shared_ptr 转换为 void* 然后再转换回 boost::shared_ptr 吗?我需要这个,因为我需要将共享指针和回调函数传递给用 C 实现的计时器函数。在回调中,我需要将 void* 指针转换回 boost:共享指针。这样做给了我错误。

我用示例程序尝试了同样的方法。

#include <iostream>
#include <boost/shared_ptr.hpp>
using namespace std;

class A
{

public:

    void f1() { cout<<"function f\n"; }
     inx aa;

private:
};

void f2 (void *arg) {

    boost::shared_ptr<A> b =  ( boost::shared_ptr<A> *)(arg);  //How to do this
}

int main ()
{
  boost::shared_ptr<A> a (new A());
  //void * ptr = (void *) &a;
  f2( (&a));

  return 0;
}

这可以用 boost::shared_ptr 来完成吗?

最佳答案

再多一个星号:

boost::shared_ptr<A> b = *(boost::shared_ptr<A>*)(arg);

关于c++ - 将 boost shared_ptr 转换为 void*,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5946927/

相关文章:

C++ Boost 链接错误

C++ boost json 解析器抑制 "No such node"输出

c++ - MSVC 和 boost::lambda::bind 错误:T0:不允许标准参数

c++ - invoke_result获取模板成员函数的返回类型

c++ - 为自定义流类设置 std::io_base 标志

c++ - 将 char* 输出到 std::string C++

c++ - Boost::signals2 传递无效数据

c++ - 打印字符数组 C++

c++ - 打印 C++ 项目中的所有代码 list

c++ - 读取文本文件并随机播放