How to create an instance of a python class from C++

Ian Kelly ian.g.kelly at gmail.com
Wed Mar 5 02:55:04 CET 2014


On Tue, Mar 4, 2014 at 5:14 PM, Bill <galaxyblue63 at gmail.com> wrote:
> Hello:
>
> I can't figure out how to create an instance
> of a python class from 'C++':
>
> ( I am relatively new to Python so excuse some of
>   the following. )
>
> In a .py file I create an ABC and then specialize it:

Why are you creating an ABC?  Most Python classes do not use them.
Maybe you have a reason for it, but it's irrelevant to what you're
currently trying to do.

> Then from 'C++' (my implementation of RegisterClass)
> I try to create an instance
>
>     static PyObject *
>     RegisterClass( PyObject *, PyObject *args ) {       // This gets called ok.
>
>         PyObject *class_decl;
>         if( ! PyArg_ParseTuple(args, "O", &class_decl) )
>             return NULL;
>         Py_INCREF(class_decl);

So far, so good.  The object that was passed in was the "Derived"
class object.  Since you presumably only want class objects to be
passed in, you might want to check that here using PyType_Check.

>         PyTypeObject *typ = class_decl->ob_type;

Okay, now if class_decl is the class object that was passed in, then
class_decl->ob_type is the *type* of that class object -- the
metaclass, which in this case would be ABCMeta.  You probably don't
need this, because you want to instantiate Derived, not ABCMeta.

>         // Tried this.
>         // PyObject *an = _PyObject_New(class_decl->ob_type); assert(an);
>         // PyObject *desc = PyObject_CallMethod(an,"description",NULL); assert(desc);

In Python, you instantiate a class by calling it.  You should do the
same in C, using PyObject_CallFunction.  But as above, note that you
want to call class_decl, not class_decl->ob_type.

PyObject_New doesn't do any initialization and is, I believe, meant to
be used when implementing types in C.



More information about the Python-list mailing list