I have been writing C code that I need to call from Python3. The C file compiles fine and I can import with ctypes
CDLL
command. Most functions work fine and I can call them from Python. I am using Python version 3.9.16.
However, I am having problems converting and manipulating small integers. I understand that Python3 uses objects for integers between -5 and 256. If I try to convert longs of this size to PyObject
in my code the script crashes.
Here's an example function in my C file:
PyObject*
convert_long_to_pyobject(long lng)
{
return PyLong_FromLong(lng);
}
If I call that from Python with the following, the second call to the function will cause a crash:
from ctypes import CDLL, c_long, py_object
dk = CDLL(my_path)
dk.convert_long_to_pyobject.argtypes = [c_long]
dk.convert_long_to_pyobject.restype = py_object
dk.convert_long_to_pyobject(257) # returns 257
dk.convert_long_to_pyobject(256) # crashes
I haven't written a full C extension. I've just written some functions in a C file, compiled it then loaded with CDLL
. I've seen that there is a function called Py_Initialize
which maybe sets up the objects for integers in the range (-5, 256) but as far as I can see it is meant for full extensions (and when I tried adding it into a function before a call to PyLong_FromLong
it didn't solve my problem.
So my question is, what do I need to do to be able to handle small integers as PyObjects in C? Particularly to convert them between C and Python.
Edit: I was previously running this from Rmarkdown which was hiding the fault returned in Python. The fault returned on the final call to the function within Python is:
Segmentation fault: 11