【问题标题】:casting void* to std::function将 void* 转换为 std::function
【发布时间】:2017-07-08 19:16:09
【问题描述】:

我有一个问题。我正在尝试将 void* 转换为 std::function。 这只是一个简单的例子,任何建议将不胜感激

#.h file
class Example {

public:

  Example();
  int foo(void* hi);

  int fooFunc(std::function<int(int, int)> const& arg, int x, int y) {
    foo(arg.target<void*>(), x, y);
    return 2;
  }

};


#.cpp file
Example::Example() {

  }

  int Example::foo(void * func, int x, int y)
  {
    //cast back to std::function
    func(x, y);
    std::cout << "running in foo: " << a << "\n";
    return a;
  }

我尝试的每一个演员都没有成功。

我知道我可以在这个例子中发送std::function,但它是为了更大的东西,我正在研究一个例子来让它在这里工作。

void* 的全部含义,是为了有时使用它,在这些情况下,当你不知道你会收到什么时,然后将它转换为你需要的特定用途。

谢谢!

【问题讨论】:

  • 你为什么这样做? void* 来自什么(一些 dlsym?)。请注意,闭包比一个指针大。
  • 一些 dsystem 库。如果我不必。我不会这样做
  • 不可能将void* 存储在std::function 中,因为它不可调用。您对target 的调用将始终返回一个空指针。
  • 我明白了..所以没有选择双向投射它?
  • 我必须使用指向 std 函数的指针?

标签: c++11 casting void-pointers std-function


【解决方案1】:

你不能。

您可以将数据指针强制转换为void*,然后返回到您开始使用的相同指针类型。 std::function 不是指针类型,因此强制转换是静态无效的,并且与您开始使用的不同。您从 void(*)() 类型的 .target 开始,但它不是数据指针,而是函数指针,因此将其转换为 void* 并返回是实现定义的。

你可以:

  1. 忽略此问题并转至void(*)()。适用于大多数(但不是全部)平台。
  2. 使用void(*)() 而不是void* 作为通用函数指针(您可以将其转换为其他函数类型)。
  3. 使用 C++ 提供的任何工具来完全避免强制转换。

【讨论】:

    猜你喜欢
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 2019-06-05
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    相关资源
    最近更新 更多