When C interacts with python, how to transfer the uncertain number of parameters?
call the module implemented by C in python to pass parameters between python and C as needed, but the number of parameters is uncertain and can be changed. May I ask how to achieve it?
all the interfaces you see now have to determine the number of parameters and specify the parameter type, such as
PyArg_ParseTuple (pTuple, "ifs", & I, & f, & s).
or simplify to the fact that the type of parameters passed is the same, but how do you implement a variable number of parameters?
for example, sometimes you want to pass 10 integers, and next time you want to pass 20 parameters?
when passing in variable parameters, use PyTuple_Size () to get the number of parameters, then use PyTuple_GetItem () loop to read each parameter value, and finally convert the parameter value according to the situation.
Please refer to the following code
/*
python :
from liyi import psum
psum(1, 2)
psum(10, 20, 30)
try:
psum('a', 1)
except TypeError:
pass
-sharp-sharp linux
cc -g -Wall `python3.6-config --cflags` -o demo demo.c `python3.6-config --ldflags`
-sharp-sharp
https://docs.python.org/3/c-api/index.html
*/
-sharpinclude <Python.h>
//
static PyObject* psum(PyObject *self, PyObject *args)
{
int sum = 0;
for (int i=0; i<PyTuple_Size(args); iPP) {
PyObject *item = PyTuple_GetItem(args, i);
//
if (!PyLong_Check(item)) {
char message[128];
snprintf(message, sizeof(message), "%d-th item must be long", i);
PyErr_SetString(PyExc_TypeError, message);
return NULL;
}
sum += PyLong_AsLong(item);
}
return PyLong_FromLong(sum);
}
static PyMethodDef Methods[] = {
{"psum", psum, METH_VARARGS, "Return sum of integer array"},
{NULL, NULL, 0, NULL}
};
static PyModuleDef Module = {
PyModuleDef_HEAD_INIT,
"liyi", NULL, -1, Methods,
NULL, NULL, NULL, NULL
};
static PyObject* PyInit(void)
{
return PyModule_Create(&Module);
}
int main(int argc, char *argv[])
{
PyImport_AppendInittab("liyi", &PyInit);
Py_Initialize();
PyRun_SimpleString(
"from liyi import psum\n"
"for numbers in [(1,2), (10,20,30)]:\n"
" print('%s = %d' % ('+'.join(map(str, numbers)), psum(*numbers)))\n"
"try:\n"
" psum('a', 1)\n"
"except TypeError:\n"
" import traceback; traceback.print_exc()\n"
);
if (Py_FinalizeEx() < 0) {
exit(1);
}
return 0;
}