简体   繁体   中英

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. 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"

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. 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 ). 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().

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