简体   繁体   English

使用 CFFI/Cython 动态包装 C 代码和 python

[英]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.我正在开发一个项目,该项目需要我在 Python 中为我需要从 Python 调用的 C 库创建一些包装器。 For context, the C library I am using is a bunch of header files (.h) and statically linked library files (.a)对于上下文,我使用的 C 库是一堆 header 文件 (.h) 和静态链接库文件 (.a)

I have decided to use either CFFI or Cython to get my work done.我决定使用 CFFI 或 Cython 来完成我的工作。 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 .对于 CFFI,我遵循了与此类似的示例 -将 C 代码与 CFFI 连接,而这对于 Cython - 使您的 C 库可从 ZA7F5F35426B927411FC9231B563821 7 通过包装调用它 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创建接口代码以调用 C API
    • In CFFI, it's a python file declaring the C functions and headers needed在 CFFI 中,它是一个 python 文件,用于声明所需的 C 函数和头文件
    • In Cython, it's a.pyx file and modifications to setup.py在 Cython 中,它是一个 .pyx 文件和对 setup.py 的修改
  • Build the interfacing code to generated the .so files for the interfacing glue code.构建接口代码以生成接口胶水代码的.so文件。
  • Call the wrapped functions from a different python script, by importing the interfacing library from the .so file.通过从.so文件导入接口库,从不同的 python 脚本调用包装函数。

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). 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 .就像,我想运行我的最终 python 脚本,它应该构建接口代码并在一次执行中即时导入它

For more context, I have tried SWIG, but wasn't able to find a way to wrapped .a statically linked libraries with it.有关更多上下文,我尝试了 SWIG,但无法找到一种方法来包装.a静态链接库。 Same goes for ctypes. 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.对于 CFFI,您只需要在运行时执行现在在构建器脚本中的代码。 Move it all in a function, and then you have a function you can call when needed.将其全部移动到 function 中,然后您有一个 function 可以在需要时调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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