我可以将函数指针 void* 强制转换为 std::function 吗?
Can I cast function pointer void* to std::function?
函数指针void*
由dlsym()
加载,我可以将其转换为std::function
吗?
假设 lib 中的函数声明是 int func(int);
using FuncType = std::function<int(int)>;
FuncType f = dlsym(libHandle, "func"); // can this work?
FuncType f = reinterpret_cast<FuncType>(dlsym(libHandle, "func")); // how about this?
不,函数类型 int(int)
和类类型 std::function<int(int)>
是两种不同的类型。 无论何时使用 dlsym
,都必须将生成的指针仅强制转换为指向符号实际类型的指针。 但在那之后,你可以随心所欲地使用它。
具体而言,您可以从指向函数的指针构造或分配std::function
:
using RawFuncType = int(int);
std::function<int(int)> f{
reinterpret_cast<RawFuncType*>(dlsym(libHandle, "func")) };
写这样的东西:
template<class T>
T* dlsym_ptr(void* handle, char const* name) {
return static_cast<T*>( dlsym( handle, name ) );
}
然后:
FuncType f = dlsym_ptr<int(int)>(libHandle, "func");
工作,它将强制转换隔离到辅助函数中。
请注意,从 void*
转换为另一种指针类型时,请使用 static_cast
。 仅当其他指针类型不起作用时才使用 reinterpret_cast
,并且static_cast
明确允许您从 void*
转换为任何其他指针类型。
相关文章:
- Confusion: decltype vs std::function
- 为什么 std::function 可以作为 std::not2 的参数?
- 'max'匹配'std::function<const int &(const int &, const int &)>'无过载
- 传递给std::function template的template参数究竟代表什么
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 将函数包装器转换为 std::function
- 类型擦除的std::function与虚拟函数调用的开销
- C++ std::function 对于类 exept 的所有实例都是空的(只有 Visual2019 编译器问题)
- 如果模板没有可变参数,则 Lambda 被推导出为 std::function
- 将 lambda 表达式传递给 std::function in C++
- 模板类的部分模板专用化,如 std::function
- 可变参数模板参数扩展 类型为 std::function 的类成员
- 从 std::function in C++ 访问模板化 lambda
- 什么是 std::function::argument_type 的替代品?
- C++派生类重载函数(带有 std::function 参数)不可见
- 如何在 qi 符号表中使用 std::function
- 将 std::function 与模板一起使用
- C++ 事件管理器的回调,使用 std::function 和 std:bind 以及派生类作为参数
- 我需要在 std::function 上使用 unique_ptr 吗?
- 如何将函数指针从 std::function 传递到 Linux 克隆?