Dmiters
Dmiters

Reputation: 2031

Python CFFI doesn't copy typedef from cdef() into generated C file

I'm feeding a generated header file into ffi.cdef(), with a bunch of typedefs like this at the beginning:

typedef enum
{
    LE_GPIO_EDGE_NONE = 0,
    LE_GPIO_EDGE_RISING = 1,
    // ...etc...
}
le_gpio_Edge_t;

Then I try to compile it:

with open(args.api_name + '_cdef.h') as f:
    cdef = f.read()

ffibuilder.cdef(cdef)
if __name__ == "__main__":
    ffibuilder.compile(verbose=True)

But it generates C code like this:

static int _cffi_const_LE_GPIO_EDGE_RISING(unsigned long long *o)
{
  int n = (LE_GPIO_EDGE_RISING) <= 0;
  *o = (unsigned long long)((LE_GPIO_EDGE_RISING) | 0);  /* check that LE_GPIO_EDGE_RISING is an integer */
  return n;
}

Which causes the build to fail, because the symbol LE_GPIO_EDGE_RISING isn't defined anywhere (or referenced anywhere else)

le_gpio.c: In function ‘_cffi_const_LE_GPIO_EDGE_RISING’:
le_gpio.c:494:12: error: ‘LE_GPIO_EDGE_RISING’ undeclared (first use in this function)
    int n = (LE_GPIO_EDGE_RISING) <= 0;

Upvotes: 0

Views: 956

Answers (1)

J.J. Hakala
J.J. Hakala

Reputation: 6214

Method ffibuilder.set_source seems to place the type definition to the generated C file.

import cffi

ffibuilder = cffi.FFI()

tdef = r"""
typedef enum
{
    LE_GPIO_EDGE_NONE = 0,
    LE_GPIO_EDGE_RISING = 1,
    // ...etc...
} le_gpio_Edge_t;
"""

ffibuilder.set_source("package._foo", tdef)
ffibuilder.cdef(tdef)

if __name__ == "__main__":
    ffibuilder.compile(verbose=True)

See documentation for c_header_source argument of set_source.

Upvotes: 3

Related Questions