Reputation: 303377
I have a class that I want to be passed around by shared_ptr
. As such, I want it to get constructed with a factory method:
py::class_<MyClass, boost::shared_ptr<MyClass>>("MyClass")
.def("__init__", py::make_constructor(MyClass::factory))
;
This worked when factory()
just took 2 arguments. But now I want it to take 2 or 3. So I used the overload macro
BOOST_PYTHON_FUNCTION_OVERLOADS(MyClass_factory_overloads, MyClass::factory, 2, 3)
But how do I pass that into make_constructor
?
Upvotes: 3
Views: 1516
Reputation: 14799
I don't think you need to use a factory in order to create a shared_ptr of MyClass. So, just define multiple init instructions:
class Foo {
public:
Foo(int, int) { std::cout << "Foo(int, int)" << std::endl; }
Foo(int, int, int) { std::cout << "Foo(int, int, int)" << std::endl; }
};
void test(boost::shared_ptr<Foo>& foo) { std::cout << &(*foo) << std::endl; }
BOOST_PYTHON_MODULE(mylib)
{
using namespace boost::python;
class_<Foo, boost::shared_ptr<Foo> >("Foo", init<int, int>())
.def(init<int, int, int>())
;
def("test", test);
}
Let's test:
import mylib
c2 = mylib.Foo(1,2)
Foo(int, int)
c3 = mylib.Foo(1,1,1)
Foo(int, int, int)
mylib.test(c2)
0x1521df0
mylib.test(c3)
0x1314370
c2a = c2
mylib.test(c2a)
0x1521df0 # the object has the same address of c2
Upvotes: 3