[C++-sig] Expose c++ class as python module

Jim Bosch talljimbo at gmail.com
Tue Nov 9 22:09:33 CET 2010


On 11/09/2010 12:31 PM, Simon W wrote:
> Hi,
> I want to export my c++ class and make an instance of it and then expose
> it to python as if it were a python module. Is it possible?
>
> // export and create instance
> class_<myClass> [...];
>
> namespace["instance"] = ptr( instanceOfMyClass );
>
>
> Then in python:
>
> import instance
>
> instance.someFunction()
>

This is not possible to do directly, as boost::python::class_ makes a 
Python type object, and that's fundamentally different from a Python 
module object.

You can simulate this by doing tricks on the Python side, however:

  - Make a regular Boost.Python module.

  - In your module-that-mimics-a-class (pure Python), instantiate your 
instance in Python as a hidden module-level variable.

  - Extract bound methods from the instance and assign them to 
module-level variables.


Jim Bosch



More information about the Cplusplus-sig mailing list