[C++-sig] Custom smart pointer with const Types

Jim Bosch talljimbo at gmail.com
Wed Oct 5 15:44:38 CEST 2011


On 10/05/2011 03:08 AM, Holger Brandsmeier wrote:
> Dear list,
>
> how should I export functions to python which return smart pointers to
> const-pointers, e.g. shared_ptr<const T>?
>
> For my own classes I always tried to avoid this problem by always
> providing a methods which returns shared_ptr<T>.
>
> Now I need to export the following method in a class provided by some
> other software package (Trilinos). Its implementation I do not want to
> change, the function is declared as
>   Teuchos::RCP<  const Teuchos::Comm<  int>  >     getComm () const
> (if you need details:
> http://trilinos.sandia.gov/packages/docs/r10.6/packages/tpetra/doc/html/classTpetra_1_1MpiPlatform.html
> )
>
> I believe I already exported the custom smart pointer `Teuchos::RCP`
> to python, I also exported the class `Teuchos::Comm<  int>` to python,
> but I get the error
>   No to_python (by-value) converter found for C++ type:
> Teuchos::RCP<Teuchos::Comm<int>  const>
> which is perfectly true, as I did not export the class `const
> Teuchos::Comm<int>`.
>
> I briefly tried to export also the const version of this class (all
> methods that I need are provided are available for the const version),
> but I failed exporting the class with varying error message, depending
> on how I tried to export it. I realized that I don't know how or even
> if I should export a const version of a type?
>
> Is there another workaround to this problem? Is there something I'm
> missing in the implementation of my custom smart pointer?
>
> I could wrap the function getComm() above to cast away the const'ness,
> but do I need to?
>
> I also found some old messages on the list titled "[Boost.Python]
> shared_ptr<const T>" with some workaround proposed by providing
> get_pointer for const T, but I believe that I have a different problem
> that I can not solve by modifying get_pointer.
>

I'm afraid you do have a different problem, though some of those ideas 
help.  Essentially, Boost.Python's support for custom smart pointers 
isn't as complete as its support for shared_ptr, and its support for 
const smart pointers is basically nonexistent.  You're pretty much in 
not-currently-supported territory.

I think wrapping getComm() to cast away the constness is going to be the 
easiest way to make this work, but if you have many such functions it 
may be worth digging deeper into the Boost.Python internals to try and 
trick it into working by specializing some templates.

Jim


More information about the Cplusplus-sig mailing list