How to neatly pass char[] to PyObject_CallMethod in Python C extension

968 Views Asked by At

I have a python object called "m1", which has a method "coor()". I will pass it to C"++" extension and call "coor()" inside. First I tried:

PyArrayObject *coor = (PyArrayObject *) PyObject_CallMethod(m1,"coor","()",NULL);

and found the following awkward code works:

char t1[]="coor, t3[]="()";
PyArrayObject *coor = (PyArrayObject *) PyObject_CallMethod(m1,t1,t3,NULL);

I believe there is a easy way to do that. This maybe a C question on char[] for a beginner, and thanks for advice.

1

There are 1 best solutions below

0
On

The documentation says:

The format may be NULL, indicating that no arguments are provided.

Additionally, there is no need for arrays. What made you think it needed arrays is likely the fact that the strings are not declared to be constant:

PyObject* PyObject_CallMethod(PyObject *o, char *method, char *format, ...)

However, they are not actually modified; look at the source; method is only passed to PyObject_GetAttrString and PyErr_SetString, both of which take const char *s. Therefore, it should be safe to cast the const char * literal into a char *, although the real solution would be for Python to change the declared parameter types to const char *.

Anyway, with that said, this:

result = object.method()

Would be roughly converted to this:

PyObject *result = PyObject_CallMethod(object, (char *)"method", NULL);