[QUESTION] How to expose pointer member with boost::python behavior
Open
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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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