V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
silencht
V2EX  ›  Python

关于 Python 利用 ctypes 导入 C 语言动态链接库的问题

  •  
  •   silencht · 2020-10-23 16:07:45 +08:00 · 1358 次点击
    这是一个创建于 1274 天前的主题,其中的信息可能已经有所发展或是发生改变。

    Linux ( Ubuntu18.04 )环境: 正在做一个项目,打算把 C 代码做成.so 动态库,然后 python 通过 ctypes 连链接使用,但是在看教程( http://blog.sina.com.cn/s/blog_4513dde60100njs8.html )的时候遇到了问题。如下:

    1.我的 c 文件,abc.c

    #include <stdlib.h>
    
    typedef struct{
      int a;
      int b;
    }mystruct;
    
    mystruct * create(){
      mystruct * s = (mystruct *)calloc(1, sizeof(mystruct));
      s->a = 100;
      s->b = 200;
      return s;
    }
    
    void destroy(mystruct * s){
      free(s);
    }
    

    通过 gcc -fPIC --shared ./abc.c -o libabc.so 编译成.so

    2.下面是我的 python 文件,abc.py

    import ctypes as ct
    class mystruct(ct.Structure):
    	__fields__=[('a',ct.c_int),('b',ct.c_int)]
    lib = ct.cdll.LoadLibrary('./libabc.so')
    lib.create.restype=ct.POINTER(mystruct)
    p = lib.create()
    p.contents.a
    p.contents.b
    

    3.同级目录下,利用$ python3 abc.py 运行,出现如下错误:

    Traceback (most recent call last):
    
    	File "abc.py",line 11,in<modele>
    
        	p.contents.a
    
    AttributeError: 'mystruct' object has no attribute 'a'
    

    4.QUESTION:为啥我重现不了教程里面的源码呢?找了很多 CSDN 和 stack flow 方面的问题,但依然解决不了。望 V 友不吝赐教,万分感激!

    6 条回复    2020-10-23 17:23:51 +08:00
    gwy15
        1
    gwy15  
       2020-10-23 16:16:41 +08:00   ❤️ 2
    _fields_,一个下划线,你打成了两个
    gwy15
        2
    gwy15  
       2020-10-23 16:17:35 +08:00
    写 python 不买游标卡尺的吗 XD
    silencht
        3
    silencht  
    OP
       2020-10-23 16:24:20 +08:00
    @gwy15 真的太谢谢你了!我一下午一头雾水。。。。用 python 没多久,被__main__两个下划线带跑偏了。真的是太感谢你了!(是时候考虑一下买一个游标卡尺了,人生苦短,我用游标卡尺..............
    silencht
        4
    silencht  
    OP
       2020-10-23 16:33:30 +08:00
    @gwy15 我还有一个问题想向您请教,您是如何看出两个下划线出现问题的呢?这个问题还可以再学一下 python 的哪些知识点加深理解?(祝您每天开心:)
    Huelse
        5
    Huelse  
       2020-10-23 16:38:58 +08:00   ❤️ 2
    程序员字体可以帮你看出来,稍微大点的库用 pybind11 来打包会更好用
    gwy15
        6
    gwy15  
       2020-10-23 17:23:51 +08:00   ❤️ 2
    @silencht 其实我觉得挺明显的,可能你就是看花了吧。一般双下划线就是 py built-in 的,__name__/__import__/__slots__ 这种,单下划线一般就是库级别的。

    另外如果你习惯翻文档的话,ctypes.Structure 下面第一个加黑加粗的就是 _fields_ 的说明。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2749 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 12:21 · PVG 20:21 · LAX 05:21 · JFK 08:21
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.