Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't create PyObject from integer [closed]

In writing a Python extension in C, I'm just trying to test some things out but realized that I can't build PyObject*s from a C int. Here a compilable code snippet that demonstrates the problem (you may have to #include <Python.h> if not on a Mac),

#include <Python/Python.h>
int main(){
    PyObject* obj = Py_BuildValue("i", 42);
    return 0;
}

But this results in Segmentation fault: 11. Based on Xcode's LLDB it looks like something is wrong when calling PyInt_FromLong?

If I try to do the same but using a double,

PyObject* obj = Py_BuildValue("d", 42.0);

It works just fine... I can't find anything online and am out of ideas - any help appreciated.

like image 336
Jared Avatar asked Apr 30 '26 04:04

Jared


1 Answers

If you're trying to embed Python in a C program, you first have to initialize Python with Py_Initialize(), and you should call Py_Finalize() when you're done.

Try this...

#include <Python/Python.h>

int main()
{
    Py_Initialize();
    PyObject* obj = Py_BuildValue("i", 42);
    Py_Finalize();
    return 0;
}

...and check out the embedding docs for some more examples.

like image 178
Aya Avatar answered May 01 '26 22:05

Aya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!