0

I was wondering if it is possible to store any Python object as a void* in Python C API which will be returned later to python as-is.

I tried to do something like this:

store_python_object(PyObject *self, PyObject *args)
{
    int retval;
    PyObject *self_capsule;
    void *stored_object;
    /* Parse input arguments */
    retval = PyArg_ParseTuple(args,
                              "OO:store_python_object",
                              &self_capsule,
                              &stored_object);
    if (!retval) {
        return NULL;
    }
    // More code here...
    // Return stored_object to python as-is
}

But this seems to have a weird behavior when storing an int for example (Again, I want to store any Python object, not only int).

  • Can you explain what you mean by "weird behavior"? Does it segmentation fault or something? – user202729 Aug 15 '21 at 04:13
  • Wait, what are you trying to do? Can't you use the correct pointer format then (if absolutely necessary) convert it to `void*`? – user202729 Aug 15 '21 at 04:15
  • Hi @user202729. I am trying to store an object given by the user (python) and not touch it (just store), and then later on return it to Python as-is. When the python passes a string it works well (the returned object looks fine), when the Python passes f-string I get segmentation fault, when I pass an int the returned number is (num+2) which I think suggests memory error. – Almog Tzabari Aug 15 '21 at 04:25
  • @user202729 what do you mean by "correct pointer format"? I want to be able to get any python object (int, float, list, custom class instance), store it, and then return it as-is. – Almog Tzabari Aug 15 '21 at 04:28
  • I don't really see why this isn't working. Possibly you should get a `PyObject*` from `PyArg_ParseTuple`, then convert to `void*` though (not 100% sure what the C rules are...). But this really needs an [mre] - there's all kind of mistakes that could be hiding in `// More code here...` – DavidW Aug 15 '21 at 08:54

1 Answers1

4

Found my problem:
I stored a python-object in C without increasing its reference counter (using Py_INCREF(PyObject *o)). So apparently the python deallocated the python-object which caused the weird behavior.

Thanks for everyone.