Difficulty calling python function from C

7 views
Skip to first unread message

Paul Smith

unread,
Aug 2, 2025, 1:42:11 PMAug 2
to cython-users
I have python 3.12 and cython 3.0.8 installed. I am trying to make a simple "Hello World" python function which I can call from a C program.

Here is the contents of my helloworld.py file:

def hw():
  print("Hello World")

Here is the contents of the caller.pyx file:

from helloworld import hw

cdef public void call_hw():
  hw()

And here is the contents of my main.c file:

#include <Python.h>
#include "caller.h"

int
main()
{
  Py_Initialize();
  call_hw();
  Py_Finalize();
}

Here are the commands I do:

> cython caller.pyx 
> gcc -g -Wall -I/usr/include/python3.12 -c caller.c 
> gcc -g -Wall -I/usr/include/python3.12 -c main.c 
> gcc -g -Wall -I/usr/include/python3.12 -o main *.o -lpython3.12 
> ./main 
Segmentation fault (core dumped) 

Here is a backtrace:

Program received signal SIGSEGV, Segmentation fault. 0x0000555555558898 in __Pyx__GetModuleGlobalName (name=0x0) at caller.c:2739 2739 result = _PyDict_GetItem_KnownHash(__pyx_d, name, ((PyASCIIObject *) name)->hash); (gdb) bt #0 0x0000555555558898 in __Pyx__GetModuleGlobalName (name=0x0) at caller.c:2739 #1 0x0000555555556d9a in call_hw () at caller.c:2002 #2 0x000055555555cef6 in main () at main.c:8

Can anyone tell me what I'm doing wrong?


da-woods

unread,
Aug 3, 2025, 1:13:02 PMAug 3
to cython...@googlegroups.com

Hi Paul,

It looks like you got a decent enough answer from the same post on Stack Overflow (https://stackoverflow.com/q/79723518/) so there probably isn't a need to go into detail here

I'll just add:

* as "bruno" says on Stack Overflow: for what you show here you don't really need Cython at all and using it isn't simplifying much. That may change as you move away from toy examples.

* if you're looking to generate a truly self-contained executable then you're likely to be frustrated - Cython doesn't provide an easy way of bundling your dependencies so you'll always have to include your "helloworld" script and (likely) some of the Python standard library.  If that's your main goal then there's better tools (PyInstaller and Nuitka both do a pretty good job of this in different ways I think).

--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/cython-users/a70a6bdd-72a2-4d55-bb35-daee92c7dfbdn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages