1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Calling python function from C

Discussão em 'Python' iniciado por Stack, Agosto 2, 2025.

  1. Stack

    Stack Membro Participativo

    I am having trouble making 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?

    Continue reading...

Compartilhe esta Página