Python Frequently Asked Questions, Release 3.9.5 Chapter 5. Extending/Embedding FAQ 60 5.5 How can I evaluate an arbitrary Python expression from C? 5.6 How do I extract C values from a Python object? 5.7 How do I use Py_BuildValue() to create a tuple of arbitrary length? 5.8 How do I call an object’s method from C? Note that since$_{PyObject_CallObject()}$ always wants a tuple for the argument list, to call a function without arguments, pass “()” for the format, and to call a function with one argument, surround the argument in parentheses, e.g. “(i)”. Call the function PyRun_String() from the previous question with the start symbol Py_eval_input ; it parses an expression, evaluates it and returns its value. That depends on the object’s type. If it’s a tuple,$_{PyTuple_Size()}$ returns its length and$_{PyTuple_GetItem()}$ returns the item at a specified index. Lists have similar functions, PyListSize() and PyList_GetItem() . For bytes,$_{PyBytes_Size()}$ returns its length and$_{PyBytes_AsStringAndSize()}$provides a pointer to its value and its length. Note that Python bytes objects may contain null bytes so C’s strlen() should not be used. To test the type of an object, first make sure it isn’t NULL , and then use PyBytes_Check() , PyTuple_Check() , PyList_Check() , etc. There is also a high-level API to Python objects which is provided by the so-called ‘abstract’ interface – read Include/abstract.h for further details. It allows interfacing with any kind of Python sequence using calls like PySequence_Length() , PySequence_GetItem() , etc. as well as many other useful protocols such as numbers ($_{PyNumber_Index()}$ et al.) and mappings in the PyMapping APIs. You can’t. Use$_{PyTuple_Pack()}$ instead. The$_{PyObject_CallMethod()}$ function can be used to call an arbitrary method of an object. The parameters are the object, the name of the method to call, a format string like that used with$_{Py_BuildValue()}$ , and the argument values: PyObject * PyObject_CallMethod(PyObject*object, const char *method_name, const char *arg_format, ...); res =PyObject_CallMethod(f, "seek","(ii)",10 ,0); if (res==NULL ) { ... an exception occurred ... } else { Py_DECREF(res); } To call, e.g., a file object’s “seek” method with arguments 10, 0 (assuming the file object pointer is “f”): This works for any object that has methods – whether built-in or user-defined. You are responsible for eventually Py_DECREF() ’ing the return value.