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

Matt mjkeyes at sbcglobal.net
Wed Oct 19 22:46:59 CEST 2005


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