simplest possible python cffi example

跟風遠走 提交于 2020-08-10 19:32:49

问题


I am trying to call a c function or c program from python using cffi, but I find most examples too complex for me to easily learn from. One of the best examples I have found is this example and I have copied that and made a slightly simpler version that I want to post here.

I would greatly appreciate any feedback on this example or I am hoping someone could make an even shorter and simpler example of using cffi in python for API out of line and inline and maybe even a super simple ABI example. I am impressed with how easy this is to call a simple adding function, a lot easier than calling c from Lua.

So it seems to work, but I am still not really sure why and not sure how well my more complex real example will work because I don't really know what I am doing. Incidentally this was the very first python program I have written or run. My 'hello world'. My purpose is to call a 1000 line c program I wrote from a python script to be run with the openlightspeed web server.


回答1:


I am using Ubuntu 19.10. First I installed Pip with apt install python-pip. Then I installed cffi with pip install cffi which also pulled in pycparser. Then I made 4 files in my home directory: add.c, add.h, build.py, and add.py which are as follows:

add.c:

#include "add.h" //if you don't have a header file you will get a warning
int addme(int a, int b)
    {
    return (a + b);
    }

add.h

int addme(int a, int b);

build.py:

from cffi import FFI
ffibuilder = FFI()
ffibuilder.cdef("int addme(int a, int b);")
ffibuilder.set_source("pyadd",'#include "add.h"',sources=["add.c"])
ffibuilder.compile()

add.py:

from pyadd.lib import addme
print(addme(2,6))

I entered python build.py which created pyadd.so which I was then able to import into my python script. Then I entered python add.py which returned 8. The first argument in set_source() is the name of the shared object that you will then import in your python script. Both "from pyadd.lib import addme" and "from pyadd import lib" seem to work but with the latter you have to refer to addme as "lib.addme". This must just be a python thing.



来源:https://stackoverflow.com/questions/58890418/simplest-possible-python-cffi-example

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!