简体   繁体   中英

Wrapping C code with python on the fly with CFFI/Cython

I am working on a project which requires me to create some wrappers in Python for the C library that I need to call from Python. For context, the C library I am using is a bunch of header files (.h) and statically linked library files (.a)

I have decided to use either CFFI or Cython to get my work done. I followed examples similar to this for CFFI -Interfacing C code with CFFI , and this for Cython - Making your C library callable from Python by wrapping it with Cython . Now small sample programs I've tried in both these modules more or less have the following steps

  • Create the interfacing code to call C APIs
    • In CFFI, it's a python file declaring the C functions and headers needed
    • In Cython, it's a.pyx file and modifications to setup.py
  • Build the interfacing code to generated the .so files for the interfacing glue code.
  • Call the wrapped functions from a different python script, by importing the interfacing library from the .so file.

Now, this works perfectly for me. But, I'll have to go through two execution steps in the process (generating the .so file, and then actually running the python script with the C API being called).

What I need is to know if there is a way to do all the above in a single execution step. Like, I want to run my final python script, and it should build the interfacing code and import it on the fly in a single execution .

For more context, I have tried SWIG, but wasn't able to find a way to wrapped .a statically linked libraries with it. Same goes for ctypes.

Can you not do this?

import os
os.system('command to build your .so here') 
...
import what_ever_you_need
...

For CFFI you just need to execute at runtime the code that is now in the builder script. Move it all in a function, and then you have a function you can call when needed.

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