Remove static declaration for cffi_start_python() in generated code
Hi,
I ran into an issue which I found a workaround for, but I think it'd be worth to improve this or at least to document the behavior better.
My scenario is an application that uses embedded Python scripts, the cffi generated sources are statically linked with the application. Python scripts can register to callbacks in the application, meaning that there are only calls from C->Python when a Python script has registered a callback with the C part of the app.
I know that a call to an @ffi.def_extern()
/ extern "Python"
function will initialize the interpreter, however in my scenario it is the Python script that decides if it wants to register any callbacks with the app or not, the application is not calling into Python by itself if the script did not register to receive callbacks.
This lead me to the problem, that Python was never initialized and thus the script has never been executed.
Last paragraph of https://cffi.readthedocs.io/en/latest/embedding.html says:
In case you need to force, from C code, Python to be initialized before the first @ffi.def_extern() is called, you can do so by calling the C function cffi_start_python() with no argument.
In the generated code the function cffi_start_python()
is declared as static
:
/* The cffi_start_python() function makes sure Python is initialized
and our cffi module is set up. It can be called manually from the
user C code. The same effect is obtained automatically from any
dll-exported ``extern "Python"`` function. This function returns
-1 if initialization failed, 0 if all is OK. */
_CFFI_UNUSED_FN
static int cffi_start_python(void)
{
if (_cffi_call_python == &_cffi_start_and_call_python) {
if (_cffi_start_python() == NULL)
return -1;
}
cffi_read_barrier();
return 0;
}
Is there any reason why it is static
if it is supposed to be used as part of the public API as mentioned in the documentation?
Basically it being static makes it impossible to use it from the main application, because linking fails:
main.c:22: undefined reference to 'cffi_start_python'
The workaround I found was to declare a wrapper function in the ffibuilder.set_source()
part of the builder script:
ffibuilder.set_source("cb_test",r"""
#include "cbtest.h"
int start_python_wrapper() {
return cffi_start_python();
}
""", sources=["cbtest.c"])
And then call the wrapper function from my main()
.
The documentation suggests that cffi_start_python()
can be called directly; how is it meant to be done or did I hit a bug in the generator?
Kind regards,
Jin
P.S. here is a small example program that I used to debug the above issue: