mixing SWIG generated and Python-level usertype?

Bo Peng bpeng at rice.edu
Wed Feb 2 02:30:18 EST 2005


Dear list,

My SWIG generated module (myModule) needs an array-like object (carray) 
to work. Carray objects are created both internally (in C++ level) and 
through Python so I have to load it when myModule initializes.

carray is modified from arraymodule.c and is quite simple:

static PyMethodDef a_methods[] =
{
   {"carray", a_array, METH_VARARGS, a_array_doc},
   {                                               /* sentinel */
     NULL,    NULL
   }
};

Currently, I load a_methods directly using code (error checking ignored)

   PyObject* mm = PyImport_AddModule("__main__");
   PyObject* dict = PyModule_GetDict(mm);
   PyObject*  v = PyCFunction_New(a_methods, NULL);
   PyDict_SetItemString(dict, a_methods->ml_name, v);

There are several problems with this approach:

1. use of __main__? carray can not be accessed directly within other 
libraries. ('from myModule import *' DOES NOT import carray!) I tried to 
use __builtins__ but it does not work for some reason out of my 
understanding of Python. I am not sure how to add carray to myModule 
dictionary.

2. No type object? I am not sure what is the purpose of ArrayType but 
the usual init_module should be
     m = Py_InitModule3("carray", a_methods, module_doc);
     d = PyModule_GetDict(m);
     PyDict_SetItemString(dict, "ArrayType", (PyObject *)&Arraytype);

When I add ArrayType to __main__ , access to ArrayType leads to a quick 
core dump.

I do not feel comfortable with my current approach. Could anyone tell me 
some better (more standard) way?

Many thanks in advance.
Bo



More information about the Python-list mailing list