ctypes error AttributeError symbol not found, OS X 10.7.5
ctypes error AttributeError symbol not found, OS X 10.7.5
我在C++上有一个简单的测试函数:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <locale.h>
#include <wchar.h>
char fun() {
printf( "%i", 12 );
return 'y';
}
编译:
gcc -o test.so -shared -fPIC test.cpp
并在python中使用ctypes:
from ctypes import cdll
from ctypes import c_char_p
lib = cdll.LoadLibrary('test.so')
hello = lib.fun
hello.restype = c_char_p
print('res', hello())
但后来我得到了一个错误:
Traceback (most recent call last): File "./sort_c.py", line 10, in <module>
hello = lib.fun File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 366, in __getattr__
func = self.__getitem__(name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 371, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: dlsym(0x100979b40, fun): symbol not found
哪里有问题?
使用:
Mac Os X 10.7.5和Python 2.7
您的第一个问题是C++名称篡改。如果你在.so
文件上运行nm
,你会得到这样的东西:
nm test.so
0000000000000f40 T __Z3funv
U _printf
U dyld_stub_binder
如果使用C++编译时将其标记为C样式:
#ifdef __cplusplus
extern "C" char fun()
#else
char fun(void)
#endif
{
printf( "%i", 12 );
return 'y';
}
nm
给出:
0000000000000f40 T _fun
U _printf
U dyld_stub_binder
您的第二个问题是,python将与Segmentation fault: 11
(在OSX上)一起死亡。C++返回一个char
,而您在python中将其标记为指向char的指针。用途:
hello.restype = c_char
相反(更改import
语句以匹配)。
编辑:正如@eryksun所指出的,您不应该使用gcc
,而应该使用g++
。否则,将不会链接正确的C++运行时。检查OS X
:
otool -L test.so
(ldd
,通常在UNIX/Linux上使用的工具,不与OS X一起分发)
相关文章:
- "ostream &os"有什么用?
- OpenCV Android C++ imwrite not found
- libprotobuf 检查在 Mac OS 上执行程序时失败
- C++读取用户输入而不按回车键(Mac OS X),与Turbo Pascal中的读取键相同
- 如何在 MAC OS c/c++ 中阻止 USB 存储设备
- 解决"ld: library not found for -ltensorflow_framework.2.3.0"
- 加载与引用 .NET DLL 位于同一文件夹中的引用的 .NET DLL 时"Not found"异常
- 处理"no operator found"
- 编译 Boost 时在 OS X 上的"ld:未知选项:-soname"
- C++初学者:为什么我的编译器根据我的循环返回"name not found"?
- _BitScanForward64 can not be found
- 在 c++ 中检查 Windows OS 服务器版本
- OS X: ld: 找不到 -lstdc++ 的库
- Python os.system() 返回错误值
- Mac os x app bundle 在下载并运行时崩溃,但在终端或更改 Info.plist 时运行良好
- const 如何防止写入特定内存 [Clang, Mac OS]
- 使用提升 asio 时出现"resolve: Host not found (authoritative)"异常
- 旧C++代码中的目录查找导致 OS X Catalina 10.15 中的目录错误
- 如何在 Mac OS 上安装 boost-mpi 及其对 clang 的依赖关系?
- ctypes error AttributeError symbol not found, OS X 10.7.5