Return a normal Python string from cffi function?

100 views Asked by At

This explanation of cffi gives an example of how to declare a C function returning a float. You can also declare it to return a char*. I have adapted this toy example:

# my_ffi.py
...

ffibuilder.cdef("""
    char * my_cfun(void);
""")

...

If I do this, then I need the following Python at the call site to get it back into a Python string:

# user.py
from _my_ffi import ffi, lib

print(ffi.string(lib.my_cfun()))

How can I declare it such that the calling Python code sees an ordinary Python string, thus not needing the conversion? I have tried using PyObject * as the return type, but this causes cdef to fail to parse it:

cffi.CDefError: cannot parse "PyObject * my_cfun(void);"

The Googleability of this application is quite bad... I suspect there is a totally different way to pass python objects back and forth, but I have also definitely seen function signatures in C that contain PyObject.

2

There are 2 answers

1
Armin Rigo On

Like relent95 said, the answer is to write this Python function:

def stuff():
    return ffi.string(lib.my_cfunc())
0
fisherdog1 On

This does not appear to be a feature of cffi. I was able to get exactly what I was imagining with C Extensions, example in this answer: Compiler can't find Py_InitModule() .. is it deprecated and if so what should I use?

This is much more similar to the Lua C API, but appears to be unrelated to cffi. I also found ctypes, which I have not yet tried.