osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Calling an unbound method in C using the Public API


29.08.18 17:33, Matthieu Dartiailh ????:
> I tried to look at the public C API for a way to call an unbound method with a minimal cost (in term of speed and memory). It seems to me, but please correct me if I am wrong, that one cannot call a MethodDef using only the public API. To use the public C API, one has to use PyCFunction_Call (or a variant) that expect a PyCFunctionObject which binds a the MethodDef to an instance. In my case, to avoid creating a temporary PyCFunctionObject each time I call list.insert on my custom subclass instance, I have to store that PyCFunctionObject for each instance. But this means storing  7 PyCFunctionObject per instance (one for each method of list I need to wrap). So I can either use the public API and increase the memory footprint or slow down the code by creating PyCFunctionObject for each call
>   , or use large amount of the private API.
> 
> Am I missing something ?

In general, you need to cache the unbound method object, and call it 
with self as the first argument.

list_insert = PyObject_GetAttrString((PyObject *)&PyList_Type, "insert");
...
res = PyObject_CallFunctionObjArgs(list_insert, self, index, value, NULL);

But in the particular case of the insert method it will be easier and 
more efficient to use PyList_Insert().