I have in Python an object such as:
JavaScript
x
10
10
1
import test
2
class Test:
3
def __init__(self, n):
4
self.n = n
5
6
t = Test(4)
7
8
test.c_function(t)
9
10
And I want to read it in c in the
JavaScript
1
13
13
1
static PyObject* py_c_function(PyObject* self, PyObject* args) {
2
PyObject obj;
3
if (!PyArg_ParseTuple(args, "O", &obj))
4
return NULL;
5
int n;
6
7
// I want to access the the n member of the object or create a new Test struct
8
return Py_BuildValue("i", n);
9
// or
10
return Py_BuildValue("i", test.n);
11
12
}
13
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.
JavaScript
1
5
1
PyObject * o = PyObject_GetAttrString(&obj, "n");
2
3
long n;
4
n = PyLong_AsLong(o);
5
But when I ran this I get the error:
JavaScript
1
2
1
SystemError: ../Objects/dictobject.c:1438: bad argument to internal function
2
edit 2
I am compiling the c code using GCC with:
JavaScript
1
2
1
gcc -I/usr/include/python3.8/ -shared -o test.so -fPIC test.c
2
and then in the python script I add
JavaScript
1
2
1
import test
2
Advertisement
Answer
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.