我可以将函数指针 void* 强制转换为 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* 转换为任何其他指针类型。

相关内容

最新更新