函数指针调用不编译
Function pointer call doesn't compile
我只是不明白,为什么第22行编译失败?
#include <stdexcept>
#include <dlfcn.h>
#include "Library.h"
int main(int argc, char *argv[])
{
try
{
void* libHandle = 0;
libHandle = dlopen("libExpandableTestLibrary.so", RTLD_LAZY);
if(!libHandle)
throw std::logic_error(dlerror());
std::cout << "Libary opened gracefully" << std::endl;
void* fuPtr = 0;
fuPtr = dlsym(libHandle, "createLibrary");
if(!fuPtr)
throw std::logic_error(dlerror());
Library* libInstance = static_cast<Library* ()>(fuPtr)();
// Tutorial: http://www.linuxjournal.com/article/3687
// Tutorial Code: shape *my_shape = static_cast<shape *()>(mkr)();
// Compiler error message: Application.cpp:22:56: error: invalid static_cast from type ‘void*’ to type ‘Library*()’
libInstance->Foo();
dlclose(libHandle);
} catch(std::exception& ex)
{
std::cerr << ex.what() << std::endl;
}
}
欢迎任何帮助如果您需要其他信息,请告诉我。
我认为fuPtr
指向一个函数,该函数应该返回一个指向Library
对象的指针(给定加载的名称是"createLibrary"
)。
在这种情况下,包括强制转换在内的行需要看起来像这样:
Library* libInstance = reinterpret_cast<Library* (*)()>(fuPtr)();
从' void* '类型转换为' Library*() '类型无效
在c++中,在对象和函数指针类型之间进行强制转换是非法的(因为它们的大小可能不同)。
大多数支持此扩展的编译器将要求您使用reinterpret_cast
甚至c风格的强制转换。
"Library*()"不计算为类型。试试"Library * (*)()"
相关文章:
- 访问条件类成员的方法不仅在被调用时才编译
- C++:编译时检查匹配的函数调用对?
- C++11:模板方法的模板函数调用无法编译?
- 编译多个C++文件.调用二进制文件以运行代码
- 内联扩展编译为函数调用 [C++]
- 使用 MINGW gcc 编译时,不会为 std::string 调用重载的新运算符
- 是否可以在编译时初始化对象的 C 样式函数指针,以便它调用对象的成员函数?
- BGL:当包含 random_spanning_tree.hpp 时,对strong_components的调用无法编译
- 如何检查在编译时是否调用了模板化方法?
- C++根据调用的构造函数强制编译时错误
- 使用 Flutter 从 Android 上的原生编译共享库中调用函数
- 为什么缺少名称的函数调用仍然可以编译
- C++:编译对无关派生类、bug或特性的函数调用
- C++编译时检查是否可以用某种类型的参数调用重载函数
- 为什么在编译此代码时会出现此错误?(在~之后调用terminate)
- 生成代码(在编译时)以调用模板的每个实例化的静态函数
- C++11 - 获取编译时的所有类变量,并在没有 Boost 的情况下为它们调用方法
- 编译为 cuda 内核调用提供了"expression must have integral or unscoped enum type"
- 无法编译 std::reduce 调用,而 std::累积调用编译相同的参数
- 为什么 gcc5.4 不编译调用非 constexpr 函数的 constexpr 函数,而 icpc 可以编译?