[C++-sig] Beginner Question on Pointers Passed to Python via Boost

Matthew B. Keyes Keyes at simcrest.com
Wed Oct 19 23:37:53 CEST 2005


One quick note:

If I use a return_value_policy of reference_existing_object, it seems to
work.  I know this is considered "dangerous" - would this be problematic
in this case?

Thanks again!

"Matt" <mjkeyes at sbcglobal.net> wrote in message
news:<dj6bk6$960$1 at sea.gmane.org>...
> Hello again,
> 
> To start with, let me provide a simple case scenario to elaborate on
what I 
> want to do:
> 
> class UserData
> {
> public:
>     UserData() : m_nID(0) {}
>     virtual ~UserData() {}
> 
>     int GetID()    {return m_nID;}
>     void SetID(int nID)    {m_nID = nID;}
> 
> protected:
>     int m_nID;
> };
> 
> class UserDataMgr
> {
> public:
>     UserDataMgr() {}
>     virtual ~UserDataMgr() {DeleteMappedUserData();}
> 
>     void RegisterUserData(int nID)
>     {
>         //do some checking to see if it already exists... left out for

> simplicity
> 
>         UserData *pData = new UserData();
>         pData->SetID(nID);
>         m_MappedUserData[nID] = pData;
>     }
> 
>     UserData * GetUserData(int nID)
>     {
>         return m_MappedUserData[nID];
>     }
> 
> protected:
>     void DeleteMappedUserData()
>     {
>         //iterate through the map and delete the pointers...
>     }
> 
>     std::map<int,UserData*> m_MappedUserData;
> }
> 
> BOOST_INIT_MODULE(MyModule)
> {
>     class_<UserData, boost::noncopyable>("UserData")
>         .def("GetID",&UserData::GetID)
>         ;
> 
>     class_<UserDataMgr>("UserDataMgr")
>         //If I understand things correctly, the below will cause
Python to 
> manage the lifetime of the UserData * returned
>         .def("GetUserData", &UserDataMgr::GetUserData, 
> return_value_policy<manage_new_object>()))
>         ;
> }
> 
> What I'm hoping to accomplish is the above scenario *without* letting
Python 
> manage the lifetime of the UserData pointer.  In other words, I want
to be 
> able to have a single copy of a UserData instance available in which
Python 
> can retrieve from the UserDataMgr and perform operations on (but not
destroy 
> or copy the underlying pointer).  Is this possible?  I'm sure this is
a 
> beginner question, but help is appreciated.
> 
> Note - I imagine that the manage_new_object return policy will be
changed, 
> but I'm simply supplying what I have for illustration.
> 
> Thanks! 



More information about the Cplusplus-sig mailing list