简体   繁体   中英

simplest possible python cffi example

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM