函数指针赋值在C中有效,但在C++中无效
Function Pointer assignment works in C but not C++
我需要在Mac OS X的运行时动态链接到库函数。以苹果为例,我声明了一个函数指针,并用dlsym((的结果为其赋值。以下示例成功编译为纯C(.C(文件。但我需要在C++文件中使用它,如果我将这个示例编译为C++文件(.cpp(,clang编译器会告诉我
无法使用类型为"void"的右值初始化类型为"void(((char*("的变量
为什么它在纯"C"中工作,我该如何解决这个问题?
#include <dlfcn.h>
void Test() {
// Load the library which defines myFunc
void* lib_handle = dlopen("myLib.dylib", RTLD_LOCAL|RTLD_LAZY);
// The following line is an error if compiled as C++
void (*myFunc)(char*) = dlsym(lib_handle, "myFunc");
myFunc("Hello");
dlclose(lib_handle) ;
}
dlsym
返回void*
。在POSIX中(但不是标准的C,正如James所指出的(,有一个从void*
到函数类型指针的隐式转换,所以对myFunc
的赋值就是有效的。在C++中没有隐式转换(因为它不是类型安全的(,所以你需要通过添加一个强制转换来告诉编译器你真正是认真的:
void (*myFunc)(char*) = (void(*)(char*))dlsym(lib_handle, "myFunc");
(或者你可以用reinterpret_cast
来获得乐趣(。
因为C编译器坏了。没有转换(显式或隐式(在void*
和指向函数,既不在C中也不在C++中。
Posix为C添加了一个限制,并要求void*
和指向函数的指针具有相同的大小和表示方式,因此即:
void (*myFunc)( char * );
*(void (**myFunc)( char* ))( &myFunc ) = dlsym(...);
将起作用。
在C++中,您可能希望使用以下内容:
class GetFunctionHelper;
GetFunctionHelper getFunction( void* dlHandle, std::string const& functionName );
class GetFunctionHelper
{
void* fromSystem;
freind GetFunctionHelper getFunction( void* , std::string const& );
GetFunctionHelper( void* fromSystem ) : fromSystem( fromSystem ) {}
public:
template <typename Ptr> operator Ptr() const
{
return *reinterpret_cast<Ptr const*>( &fromSystem );
}
};
GetFunctionHelper
getFunction( void* dlHandle, std::string const& functionName )
{
return GetFunctionHelper( dlsym( dlHandle, functionName.c_str() ) );
}
(当然还有更多的错误检查(。
相关文章:
- 代码在main()中运行,但在函数中出现错误
- 链接阶段在Ubuntu上失败,但在MacOS上失败
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 断言中的Fold表达式在某些计算机上编译,但在其他计算机上不编译
- 换位表导致测试失败(但在游戏中运行良好)
- 库标题在标题中不可见,但在 cmake build 下.cpp文件中完全可见.为什么?
- 树莓上的 Libtorch 无法加载 pt 文件,但在 ubuntu 上工作
- 在成员dynamic_bitset上使用 boost::from_block_range 时出错,但在本地dynamic
- 编译在我的 Mac 上工作,但在集群 (Linux) 上不起作用
- 我编写了代码将十进制分数转换为其二进制等效数.它编译得很好,但在执行时挂起
- 我的代码运行良好,但在游戏循环中中断
- C++ assigment std::list:<typename>:itrator 在 main 中工作,但在方法中它不起作用
- C++代码在台式机上工作正常,但在笔记本电脑上则不行
- 实现 DFS 在较短的输入下工作正常,但在较大的输入下会抛出分段错误
- 点云库在VS 2019中不起作用,但在VS 2017中确实有效
- C++ Python 模块在 Blender 中崩溃,但在 Python 控制台中不会崩溃
- 分段 Linux Ubuntu 中的 g++ 错误,但在 Windows 中的 g++/MingW 中,在 C++ 中打
- 为什么数组大小信息可用于"sizeof"运算符和 delete[] 运算符,但在将数组作为参数传递到
- 如何处理没有默认构造函数但在另一个构造函数中构造的对象?