您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – ctypes错误找不到AttributeError符号,OS X 10.7.5

5b51 2022/1/14 8:23:30 python 字数 3448 阅读 573 来源 www.jb51.cc/python

我在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 -fP

概述

#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

并在使用ctypes的python中使用它:

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 and Python 2.7

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故障而死:11(在OS X上). C返回一个char,而你在python中将它标记为指向char的指针.使用:

hello.restype = c_char

相反(改变你的import语句来匹配).

编辑:正如@eryksun所指出的,你不应该使用gcc,你应该使用g代替.否则,将不会链接正确的C运行时.要检查OS X:

otool -L test.so

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

总结

以上是编程之家为你收集整理的python – ctypes错误找不到AttributeError符号,OS X 10.7.5全部内容,希望文章能够帮你解决python – ctypes错误找不到AttributeError符号,OS X 10.7.5所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶