Learning to use CFFI

44 views
Skip to first unread message

Eric Gorr

unread,
Apr 13, 2018, 7:52:03 PM4/13/18
to python-cffi
Hello. I am trying to learn cffi. I have a sample project at https://github.com/EricG-Personal/cffi_test which closely mimics my real situation.

It has the following folder structure:

cffi_test
c_library/
build_sample_lib.py
sample_lib.c
sample_lib.h
cffi_test/
__init__.py
cffi_test.py
setup.py

After I do:

pip install -e .

I get the following additional files:

cffi_test
_sample_lib.abi3.so
_sample_lib.c
_sample_lib.cpython-36m-darwin.so
_sample_lib.o
build/
<various build files>
cffi_test.egg-info/
<various egg-info files>

Then, If I try:

python
from cffi_test import cffi_test

I get an import error claiming that it cannot find _sample_lib.

Which, of course, it cannot, because _sample_lib.cpython-36m-darwin.so was not put into the 'cffi_test/cffi_test' package directory.

If I manually move _sample_lib.cpython-36m-darwin.so into cffi_test/cffi_test, I can:

python
from cffi_test import cffi_test
cffi_test.a_python_function(10)

and it will correctly print:

a_sample_function: 10

So, I can build everything correctly, but I am not sure what the best way is to have the built library placed inside of the package on an install.

My setup.py looks like:

from setuptools import setup, find_packages

requirements = [
'cffi'
]

setup_requirements = [
'cffi'
]

setup(
name = 'cffi_test',
packages = find_packages( include = [ 'cffi_test' ] ),
install_requires = requirements,
setup_requires = setup_requirements,
cffi_modules = [ "c_library/build_sample_lib.py:ffibuilder" ]
)

There is likely various ways to reorganize things and I am wondering what the best practices are in this situation.

Armin Rigo

unread,
Apr 15, 2018, 5:21:06 AM4/15/18
to pytho...@googlegroups.com
Hi Eric,

I think you need to say

ffi.set_source("cffi_test._sample_lib",

instead of just

ffi.set_source("_sample_lib",

which should ensure that the .so is correctly placed inside the
cffi_test package.


Armin

Eric Gorr

unread,
Apr 15, 2018, 8:09:15 PM4/15/18
to python-cffi
Thank you. 

That did work and I pushed the change. Hopefully, others may find this example useful. 

I was wondering if you (or anyone else) had any comments on what my setup.py or build_sample_lib.py looks like. Is it pretty standard or is there something better I could be doing?
Reply all
Reply to author
Forward
0 new messages