[C++-sig] Private construction for python objects?
Stefan Seefeld
seefeld at sympatico.ca
Fri Oct 24 21:34:13 CEST 2008
Robert Dailey wrote:
> Hi,
>
> I have a C++ class that I'm exposing to Python via the Boost.Python
> library. This specific class is only created from C++. In other words,
> it doesn't serve the user very much good to construct an instance of
> this class from Python. A typical use case for obtaining an instance
> of this class from python is as follows:
>
> import myCustomModule
> fooInstance = myCustomModule.GetFooInstance()
>
> However, I want to prevent the user from being able to do this:
>
> import myCustomModule
> fooInstance = myCustomModule.Foo()
>
> Let's assume the class in question with private construction is Foo.
> The latter code snippet would be an example of the user directly
> constructing an instance of Foo(). Is there a way to prevent this
> through the BOOST_PYTHON_MODULE() definition? I'm not even really sure
> if this can be done natively through Python. Thanks.
You can specify a 'noinit<>' argument to the class_<> constructor,
indicating you don't want this to expose any constructor. Then, you may
use make_constructor to provide your own custom construction (factory)
function instead.
Please look for details in the online tutorial and reference manual, as
well as the examples / tests that are part of the sources.
HTH,
Stefan
--
...ich hab' noch einen Koffer in Berlin...
More information about the Cplusplus-sig
mailing list