Re: Creating class instances in C Andrew KUCH

Andy Bensky (ab@infoseek.com)
29 Jun 1994 23:41:24 GMT

In article 73l@homer.cs.mcgill.ca, fnord@cs.mcgill.ca (Andrew KUCHLING) writes:
>attributes. Is there any way for an extension module written in C to
>find the class "Item", create an instance of it, and then add various
>attribute variables to the new instance?
>

I'm surprised no one has answered this yet, so I'll have a go at it.

It is easy to instantiate a Python object and then load it up with attributes
from within C. What it can't do is find the class object, that must be passed in.
Here is the method to use:

1. Define the class in python. You must define a method to be used to set each of
the attributes you want to be able to set values for from within C that you will not
be setting in the constructor (__init__)
eg:
class foo_class:
def __init__(self,val):
attr_1 = val
def set_attr2(self, val):
attr_2 = val

2. Write a C interface using the methods described in the Extensions manual.
This interface must have a function defined which takes a single parameter which
is an "O" type object as interpreted by getargs() and stores it as an (object *). in C.
eg:
object *foo_class_handle
object * register_class_handle( object *self, object *arg )
{
XDECREF(foo_class_handle);
foo_class_handle = arg;
XINCREF(foo_class_handle);
XINCREF(None);
return( None );
}

3. Before you go into the section of C code which needs to instantiate an object of
your python-defined class, you must call the function described in (2) to register
a handle to the class you want to work with.
eg:
import cmodule
cmodule.register_class_handle(foo)

4. Within your C code you are now free to make instances of the class you defined
and registered a handle to. Do this by using the call_object() function with the
resgistered class object handle as the first param. The second paramter to call_object()
must be a tuple consisting of the arguments to the constructor. You can make this
by using mkvalue() or mktuple().
eg:
args = mkvalue( "(i)", 10)
new_foo_class_instance = call_object(foo_class_handle, args)

5. Now you have an object in C that is of a class you defined in Python.
To get a handle to the bound methods for the particular instance you use the
getattr() call passing it the object instance and the method name as a string.
eg:
set_method = getattr(foo_class_handle, "set_attr2")

6. To set the values of various attributes you call the methods of that object that were
defined to set those attributes. Call the methods using call_object(), but remember to
pass in the object itself as the first element in the argument list tuple.
eg:
args = mkvalue( "(Oi)", new_foo_class_instance, 20)
call_object(set_method, args)

I hope this helps.

andy bensky
InfoSeek Corp.