[C++-sig] Providing a Package from a single Extension?

Ult Mundane ult at mundane.org
Mon Jul 18 17:11:58 CEST 2005


Hi there,

I would like to create a single python extension that provides a package 
structure (multiple submodules).

Here's why I think this is the best thing to do, please advise if there's a 
better way to achieve the same result:

I'm embedding python in a statically linked application. Because the python 
modules will be statically linking to common libraries and I'd like only one 
copy of each library at runtime, I'm statically linking the modules into the 
application.

My question is, what's the best way to provide a package from a static 
application embedding python?

The following code is how I'm approximating it. It allows python code running in 
the embedded interpreter to "import pyext" which in turn provides 
"pyext.submodule". It doesn't, however, allow "import pyext.submodule", which a 
real package made of multiple shared modules would allow. Are there any other 
ways I might be disturbing the order of things by this unconventional approach? 
Is there a more conventional approach to do the same thing?

Thanks,

Ult

---

#include <Python.h>
#include <boost/python.hpp>

#include <iostream>

using namespace boost::python;

void func(char const * str)
{
   std::cout << str << std::endl;
}

BOOST_PYTHON_MODULE(submodule)
{
   def("func", func);
}

BOOST_PYTHON_MODULE(pyext)
{
   def("func", func);

   initsubmodule();

   object submodule((
       handle<>(borrowed(PyImport_AddModule("submodule")))));

   scope().attr("submodule") = submodule;
}

int main(int argc, char * argv[])
{
   Py_Initialize();

   initpyext();

   Py_Main(argc, argv);

   Py_Finalize();
}



More information about the Cplusplus-sig mailing list