找不到ctypes错误AttributeError符号,OS X 10.7.5 [英] ctypes error AttributeError symbol not found, OS X 10.7.5

查看:108
本文介绍了找不到ctypes错误AttributeError符号,OS X 10.7.5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++上有一个简单的测试功能:

I have a simple test function on 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:

and using it in python with 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

Mac Os X 10.7.5 and Python 2.7


推荐答案

您的第一个问题是C ++ 名称修改。如果在 .so 文件上运行 nm ,您将得到如下内容:

Your first problem is C++ name mangling. If you run nm on your .so file you will get something like this:

nm test.so
0000000000000f40 T __Z3funv
                 U _printf
                 U dyld_stub_binder

如果使用C ++编译时将其标记为C风格:

If you mark it as C style when compiled with 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错误而死:11 (在OS X上)。 C ++返回 char ,而您在python中将其标记为指向char的指针。使用:

Your second problem is that the python will die with a Segmentation fault: 11 (on OS X). The C++ is returning a char, whereas you are marking it in python as a pointer to a char. Use:

hello.restype = c_char

代替(更改您的 import 语句以匹配)。

instead (alter your import statement to match).

编辑:正如@eryksun指出的那样,您不应使用 gcc ,而应使用 g ++ 。否则,将不会链接正确的C ++运行时。要检查 OS X

as @eryksun pointed out, you should not use gcc, you should use g++ instead. Otherwise the correct C++ runtime will not be linked. To check on OS X:

otool -L test.so

ldd ,通常在UNIX上使用的工具/ Linux,不随OS X一起分发)

(ldd, the tool normally used on UNIX/Linux, is not distributed with OS X)

这篇关于找不到ctypes错误AttributeError符号,OS X 10.7.5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆