How to create instances of classes in extension module?

Fredrik Lundh effbot at telia.com
Wed Aug 30 03:57:00 EDT 2000


uwe wrote:
> How can I create an instance of a python class in an extension module? 
> 
> More in detail:
> 
> I have a class written in python and an extension module written in C. The 
> extension module exports a function that should return an instance of the 
> class. But how do I create an instance of that class in my C-code?

something like this might work (based on code in _sre.c)

PyObject*
mycall(char* module, char* function)
{
    PyObject* name;
    PyObject* module;
    PyObject* func;
    PyObject* result;

    /* get module */
    name = PyString_FromString(myModule);
    if (!name)
        return NULL;
    module = PyImport_Import(name);
    Py_DECREF(name);
    if (!module)
        return NULL;

    /* get factory function */
    func = PyObject_GetAttrString(module, function);
    Py_DECREF(module);
    if (!func)
        return NULL;

#if defined(HAVE_ARG_TUPLE)
    /* call object with arguments in a tuple */
    result = PyObject_CallObject(func, args);
    Py_DECREF(func);
#else
    /* ...or call object with C arguments */
    result = PyObject_CallFunction(func, "i", 10)
    Py_DECREF(func);
#endif

    return result;
}

see the C/API guide and Include/abstract.h for more
variations on the PyObject_Call theme.

</F>

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->




More information about the Python-list mailing list