pybind / pybind/pybind11

[QUESTION] How to expose pointer member with boost::python behavior

Open
#3,107 2 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C++
Stars
18k
Forks
2.3k
Avg merge
5d 17h
Merged PRs (30d)
10

Description

Hello!
I am migrating from boost::python to pybind11 and have just faced some pointer member behavior issue:

class SomeClass
{
};
struct SomeStruct
{
public:
    SomeClass* scPtr;
};

void foo( SomeStruct& str )
{
    if ( str.scPtr )
        *str.scPtr;
}

// pybind11 version
PYBIND11_MODULE( mod, m )
{
    pybind11::class_<SomeClass>( m, "SomeClass" ).def( pybind11::init<>() );
    pybind11::class_<SomeStruct>( m, "SomeStruct" ).def( pybind11::init<>() ).
        def_readwrite( "scPtr", &SomeStruct::scPtr);
    m.def( "foo", &foo );
}

// boost python version
BOOST_PYTHON_MODULE( mod )
{
    boost::python::class_<SomeClass>( "SomeClass" );
    boost::python::class_<SomeStruct>( "SomeStruct" ).
        add_property( "scPtr", 
            boost::python::make_getter( &SomeStruct::scPtr, boost::python::return_value_policy<boost::python::reference_existing_object>() ),
            boost::python::make_setter( &SomeStruct::scPtr, boost::python::return_value_policy<boost::python::reference_existing_object>() ) );
    boost::python::def( "foo", &foo );
}

Python behavior

import mod
#boost version
stru = mod.SomeStruct()
stru.scPtr = mod.SomeClass()
mod.foo(stru) #works ok, but in pybind this will cause access violation (as far as scPtr will be spoiled)

#pybind version
stru = mod.SomeStruct()
sc = mod.SomeClass()
stru.scPtr = sc
mod.foo(stru) #works ok

So can I make pybind11 work as boost python?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the access violation using the shown pybind11 module with SomeClass, SomeStruct::scPtr, and foo, then compare it with the Boost.Python add_property binding. Check the pybind11 class_ and def_readwrite behavior for pointer members; done means establishing whether equivalent lifetime behavior is supported and documenting the required binding approach.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
api
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.