Re: calling instance methods from C

Guido.van.Rossum@cwi.nl
Tue, 20 Sep 1994 13:41:23 +0200

> I am working in a C module that has pointers to some user defined objects
> from python. I need to be able to call methods of these instances
> and am not having much uck with call_object(). I've tried using
> getattr(object,"method_name") and using call_object on what is returned,
> but I can't seem to get it to work. call_object is constantly returning 0.
>
> here is a sample:
>
> c_get_stuff_method(object *my_object)
> {
> object *arglist;
> object *result;
>
> if ( my_object )
> {
> arglist = mkvalue("(O)", None);
> /* xtra note: what ever happened to mktuple()???? */
> result = call_object(getattr(my_object,"MethodName"),arglist);
> DECREF(arglist);
> }
> }

If my_object.MethodName takes no arguments (apart from self) then a
call to mkvalue("()") should be used to create an empty tuple. BTW
mktuple was a typo in the Extending manual -- it's actually called
newtupleobject().

Also note that getattr() returns a "new" object (i.e. you should
DECREF() the result).

If all this doesn't help, I suggest calling print_error() to see what
exception you are getting -- maybeyour Python code raises an exception?

BTW it should be trivial to write a function that does all this for
you -- its signature would be

call_method(object *, char *, char *, ...)

and you would call it like this:

result = call_method(my_object, "MethodName", "()")

the last argument would actually be a mkvalue argument. I guess the
implementation would be (unchecked):

object *call_method(object *inst, char *methodname, char *format, ...)
{
object *method;
object *args;
object *result;
va_list va;
method = getattr(inst, methodname);
if (method == NULL) return NULL;
va_start(va, format);
args = vmkvalue(format, va);
va_end(va);
if (args == NULL) {
DECREF(method);
return NULL;
}
result = call_object(method, args);
DECREF(method);
DECREF(args);
return result;
}

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>