简体   繁体   English

如何使用 CFFI 将包含其标头的 C 库包装到 python 程序中?

[英]How do I wrap a C-library including its header into a python program using CFFI?

from cffi import FFI
ffi = FFI()
header_path = '/usr/include/libelf.h'
with open(header_path) as f:
      ffi.cdef(f.read())
lib = ffi.dlopen('/usr/local/lib/libelf.so')

The code above is the one I am actually struggling with.上面的代码是我真正在苦苦挣扎的代码。 For using some functions of libelf , I need to wrap the library and the header.为了使用libelf 的一些函数,我需要包装库和头文件。 After long time of recherche this seems to be the right approach to do that.经过长时间的研究,这似乎是做到这一点的正确方法。

But I get a parsing error:但我得到一个解析错误:

cannot parse "#ifndef _LIBELF_H"无法解析“#ifndef _LIBELF_H”

It seems that all kinds these expressions cause parsing errors.似乎所有这些表达式都会导致解析错误。 How can I solve this problem?我怎么解决这个问题? Or is there another approach of wrapping both: library and header?或者是否有另一种包装方法:库和标头?

ffi.cdef() is not capable of handling preprocessor directives. ffi.cdef() 不能处理预处理器指令。 The purpose of ffi.cdef() is to specify objects that are shared between python and C. It is not compiled ( this example does not call any C compiler ). ffi.cdef() 的目的是指定在 python 和 C 之间共享的对象。它没有被编译( 这个例子没有调用任何 C 编译器)。 Either you eliminate all preprocessor directives from your filestream f or you cherrypick those header parts that you actually need and copy-paste them into your ffi.cdef().要么你消除你的FILESTREAM所有预处理指令f或您cherrypick这些头部分,你确实需要,并将它们复制并粘贴到您ffi.cdef()。

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

相关问题 如何使用C库刷新Python程序中的内存? - How do i flush memory in a Python program with C-library? 如何使用Python CFFI正确包装C库 - How to properly wrap a C library with Python CFFI 我如何在SWIG中包装一个C库,而SWIG通常在C编译期间被链接? - How can I wrap a C-Library in SWIG, which has usually to be linked during C-compilation? 如何在Windows上使用64位Python调试(可能与C库相关的)内存问题? - How can I debug (potentially C-library related) memory issues using 64-bit Python on Windows? 将 C 库与 Cython 一起使用时出现错误 - I get an error, when using C-library with Cython 如何使用Python的CFFI将指针传递给C函数? - How do I pass a pointer to a C function with Python's CFFI? 从 Python (ctypes) 调试 C 库 - Debug C-library from Python (ctypes) 如何使用cffi嵌入在C语言中返回字符串的Python函数? - How can I embed a Python function that returns a string in C using cffi? cffi:如何将字符串字符的地址发送给C函数? - cffi: How do i send the address of a character of a string to a C function? 如何用 python-cffi 包装 C 函数以便 pythons 关键字参数起作用? - How to wrap a C-function with python-cffi so that pythons keyword-arguments work?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM