Home > OS >  How can I parse an object in a python c-extention?
How can I parse an object in a python c-extention?

Time:02-28

I have in Python an object such as:

import test
class Test:
    def __init__(self, n):
        self.n = n

t = Test(4)

test.c_function(t)

And I want to read it in c in the

static PyObject* py_c_function(PyObject* self, PyObject* args) {
  PyObject obj;
  if (!PyArg_ParseTuple(args, "O", &obj)) 
    return NULL;
  int n;
  
  // I want to access the the n member of the object or create a new Test struct
  return Py_BuildValue("i", n); 
  // or
  return Py_BuildValue("i", test.n);  

}

How can I access the members inside a pyObject for custom python data structures?

How can I do the opposite thing, assign values to an object that will later be called inside python?

edit:

As suggested by kpie, using the function PyObject_GetAttrString according to the documentation this should be equivalent to obj.n.

  PyObject * o = PyObject_GetAttrString(&obj, "n");
  
  long n;
  n = PyLong_AsLong(o);

But when I ran this I get the error:

SystemError: ../Objects/dictobject.c:1438: bad argument to internal function

edit 2

I am compiling the c code using GCC with:

 gcc -I/usr/include/python3.8/ -shared -o test.so -fPIC test.c

and then in the python script I add

import test

CodePudding user response:

The function PyObject_GetAttrString(obj,"attr") can read the attributes of a python class similarly to obj.attr as commented by kpie.

The issue was PyObject obj; that was not a pointer.

  • Related