Hi,
On Mon, 22 Jul 2024 at 21:44, Victor Blomqvist <
v...@viblo.se> wrote:
> In my case windows support is important. Many users there..
> On the other hand, I don't need to do some generic solution, it's enough it works for my case, and I could even modify (within reason) the c-library Im using.
>
> I got another idea from that comment thread: Its not possible to call PySys_WriteStdout and related functions from the c-code with CFFI, is it?
No, you can't reasonably call PyXxx functions from C code in CFFI
(there are hacks to do it). Better is to make a CFFI callback:
ffibuilder.cdef("""
extern "Python" void _print(const char *);
""")
and at runtime:
from _my_example import ffi, lib
@ffi.def_extern()
def _print(msg):
sys.stdout.write(ffi.string(msg).decode('utf-8', 'replace'))
# or log it, or do whatever
From the C code, you either directly call _print("somestring\n");, or
you make a wrapper for varargs, something like this which you can put
into ffi.set_source():
void my_printf(const char *format, ...)
{
va_list args;
char buffer[SOME_MAXIMUM_SIZE];
buffer[0] = 0;
va_start(args, format);
vsnprintf(buffer, sizeof(buffer), format, args);
va_end(args);
_print(buffer);
}
Then you compile the library with these lines added to some header:
extern void my_printf(const char *format, ...);
#define printf my_printf // optionally, will replace all calls
to printf automatically
Hope this helps,
Armin