Static create methods in boost python - c++

I am trying to create an object using boost python. The class definition (pseudocode):
class Awrap : public A, public boost::python::wrapper<A> {
static std::shared_ptr<A > Create(...) { ... } // inherited from A
virtual double foo(...) override { // overrides pure virtual function in A
return this->get_override("foo")(...);
}
};
BOOST_PYTHON_MODULE() {
using namespace boost::python
class_<Awrap,std::shared_ptr<Awrap>, boost::noncopyable>("A",boost::python::no_init)
.def("Create",&A::Create).staticmethod("Create")
.def("foo",pure_virtual(&Awrap::foo));
boost::python::register_ptr_to_python<std::shared_ptr<A> >();
}
The problem is that when I implement the child in python and call the static create method it creates a pointer to Awrap (not the child). So it cannot find the python-implemented version of "foo". If I implement foo in the Awrap class instead of the python child it works fine, but I don't want to do this!
Any suggestions?
Thanks!

You need to expose both Awrap::foo and A::foo to boost python. See example in:
http://www.boost.org/doc/libs/1_54_0/libs/python/doc/tutorial/doc/html/python/exposing.html

Related

Duplicated singleton when using shared library

I am trying to bind a shared library in Python using pybind11.
I created a simplified version, that illustrates the problem.
From python I call the function foobar.
This function calls a static function, that calls a factory, that again calls a factory, that constructs the Singleton.
This works fine when I run the code as a executable (without using the binder).
The problem is that when the library is used with the binder through Python, the Singleton gets constructed twice (e.i, with every use of the Singleton).
Once in the constructor of Factory2 and later in the foobar function.
I have already tried what other solutions here suggest by hiding the factories, but that didn't work or I might have implemented it wrong.
Any ideas on how this could be solved, so that the singleton only gets constructed once?
Any help would be greatly appreciated!
I created a small example that illustrates the problem.
Main.cpp:
int foobar(){
Singleton::createModel();
Singleton::getModel(); //SECOND CALL TO CONSTRUCTOR
return 0;
}
Singleton.h:
class Singleton {
public:
static void createModel(){
Factory factory;
}
static void setModel(Model *model) {
Singleton::getInstance().model = model;
}
static Model *getModel() {
return Singleton::getInstance().model;
}
private:
static Singleton &getInstance() {
static Singleton instance;
return instance;
}
Singleton() : model(nullptr) {};
~Singleton() {};
Model *model;
};
Factory.h:
class Factory {
public:
Factory(){
Factory2 factory2;
}
};
Factory2.h:
class Factory2 {
public:
Factory2();
};

C++ Passing member function reference from a class instance to another class instance

I'm very new to C++ and I'm struggling on a project where I need to transmit a reference to a callback method between to different class instances. I know that this subject is a pretty common issue for C++ beginners. I understand that member function pointers are different from the "standard" function ones, but I cannot find any post that adresses my specific problem (but may be it is because, given my lack of experience with C++ I don't understand the provided answers).
The system I try to develop is based on :
A ControllerManager class (which is a Singleton)
A Controller base class
Some specific Controller classes (FanController, LighController, etc) which inherits from the Controller class
What I would like to do is from let say a FanController instance to call an addCallback method of the ControllerManager class. This method would take as a parameter a pointer to any public method of the FanController so that the ControllerManager could made a callback to this method later (I must specify that the ControllerManager include the definition of the Controller class but doesn't know anything about the FanController class)
So far I didn't found any working solution, the only thing I managed to get is a very poor workaround (for simplicity, only relevant methods are indicated) :
class Controller {
public:
virtual void callback();
};
class FanController:Controller {
public:
virtual void callback();
};
class ControllerManager
{
private:
static ControllerManager *_instance;
Controller *_controller;
public:
void addCallback(Controller * controller)
{
_controller = controller;
}
static void periodicCallback()
{
_instance->_controller->callback();
}
};
At runtime the FanController instance provides a reference of herself to the ControllerManager singleton :
ControllerManager::getInstance()->addController(this);
and the ControllerManager can make a call to the callback method of the FanController instance:
_instance->_controller->callback();
This workaround is very limited since it allows only calls to methods declared by the parent Controller class.
What I would to implement is a system that allows the specifics controllers to provide references of their member methods (which doesn't exist in the Controller class) to the ControllerManager so that it can make calls to those methods.
If someone can help me I thanks him/her in advance.
The modern way of tackling this is to squirrel away the method's binding in a lambda.
#include <functional>
#include <vector>
class Controller {
std::vector<std::function<void()>> callbacks_;
public:
void addCallback(std::function<void()> cb) {
callbacks_.push_back(std::move(cb));
}
void periodicCallback() {
for(const auto& cb : callbacks_) {
cb();
}
}
};
class Fan {
public:
void whatever() {}
void register_in_controller(Controller* tgt) {
tgt->addCallback([this]{whatever();});
}
};

Wrapping C# C++

I would like to wrap a native library with C++/CLI. It's work with primitive type. But in the following case, it's more complicated :
interface ISampleInterface
{
void SampleMethod();
}
public ref class NativeClassWrapper {
NativeClass* m_nativeClass;
public:
NativeClassWrapper() { m_nativeClass = new NativeClass(); }
~NativeClassWrapper() { delete m_nativeClass; }
void Method(ISampleInterface ^i) {
???
m_nativeClass->Method(i);
}
};
How to wrap this ? Because the native code C++ doesn't know the ISampleInterface type... (Same question with a virtual class)
Thanks you.
There are some mistakes in the code snippet. Let's start with a clean example, declaring the native class first:
#pragma unmanaged
class INativeInterface {
public:
virtual void SampleMethod() = 0;
};
class NativeClass {
public:
void Method(INativeInterface* arg);
};
And the managed interface:
#pragma managed
public interface class IManagedInterface
{
void SampleMethod();
};
So what you need is a native wrapper class that derives from INativeInterface so that you can pass an instance of it to NativeClass::Method(). All that this wrapper has to do is simply delegate the call to the corresponding managed interface method. Usually a simple one-liner unless argument types need to be converted. Like this:
#pragma managed
#include <msclr\gcroot.h>
class NativeInterfaceWrapper : public INativeInterface {
msclr::gcroot<IManagedInterface^> itf;
public:
NativeInterfaceWrapper(IManagedInterface^ arg) : itf(arg) {};
virtual void SampleMethod() {
itf->SampleMethod();
}
};
Now your method implementation becomes easy:
void Method(IManagedInterface^ i) {
NativeInterfaceWrapper wrap(i);
m_nativeClass->Method(&wrap);
}
If your native class needs to callback into .NET code, you need to use the gcroot template. Wuth this you can store the managed object in an unmanaged class. In this unmanaged class you can then use a native "callback" and then use the member stored in `gcroot´ to callback into managed code (ISampleInterface).
See also:
How to: Declare Handles in Native Types
How to: Hold Object Reference in Native Function
Best Practices for Writing Efficient and Reliable Code with C++/CLI

Implement a pure virtual function of a shared library and calling it in the lib

I want to implement a pure virtual function of a shared lib and call it in a lib-function. This lib-function will be called in the constructor of the lib. The class which contains the pure virtual function is in an own namespace. It looks like this:
//shared lib class:
namespace A{
namespace B{
class SharedLibClass : public object{
public:
SharedLibClass(){init();}
protected:
virtual const object* func()const=0;
private:
void init(){const object* obj=func();}
}
}//namespace B
}//namespace A
//implementation class using the shared lib:
class B : public A::B::SharedLibClass
{
protected:
virtual void func(){return this;}
}
This are my classes. I can compile them without problems, but when I run it, Qt prints out the following error:
pure virtual method called
terminate called without an active exception
I could imagine the problem is, that the parent class calls the virtual function before it is initialised or something like that. How can I solve this problem?
You can't declare function void and then return something from it. And you need to declare your function with exactly the same signature if you want to make it implementation of existing pure virtual function:
class B : public A::B::SharedLibClass {
protected:
virtual const object* func() const { /* your implementation */ }
}
Any good compiler recognizes these issues in compilation time. Check error reporting, maybe something is wrong in your build process (maybe your file isn't compiled at all?).

Registering derived classes in C++

EDIT: minor fixes (virtual Print; return mpInstance) following remarks in the answers.
I am trying to create a system in which I can derive a Child class from any Base class, and its implementation should replace the implementation of the base class.
All the objects that create and use the base class objects shouldn't change the way they create or call an object, i.e. should continue calling BaseClass.Create() even when they actually create a Child class.
The Base classes know that they can be overridden, but they do not know the concrete classes that override them.
And I want the registration of all the the Child classes to be done just in one place.
Here is my implementation:
class CAbstractFactory
{
public:
virtual ~CAbstractFactory()=0;
};
template<typename Class>
class CRegisteredClassFactory: public CAbstractFactory
{
public:
~CRegisteredClassFactory(){};
Class* CreateAndGet()
{
pClass = new Class;
return pClass;
}
private:
Class* pClass;
};
// holds info about all the classes that were registered to be overridden
class CRegisteredClasses
{
public:
bool find(const string & sClassName);
CAbstractFactory* GetFactory(const string & sClassName)
{
return mRegisteredClasses[sClassName];
}
void RegisterClass(const string & sClassName, CAbstractFactory* pConcreteFactory);
private:
map<string, CAbstractFactory* > mRegisteredClasses;
};
// Here I hold the data about all the registered classes. I hold statically one object of this class.
// in this example I register a class CChildClass, which will override the implementation of CBaseClass,
// and a class CFooChildClass which will override CFooBaseClass
class RegistrationData
{
public:
void RegisterAll()
{
mRegisteredClasses.RegisterClass("CBaseClass", & mChildClassFactory);
mRegisteredClasses.RegisterClass("CFooBaseClass", & mFooChildClassFactory);
};
CRegisteredClasses* GetRegisteredClasses(){return &mRegisteredClasses;};
private:
CRegisteredClasses mRegisteredClasses;
CRegisteredClassFactory<CChildClass> mChildClassFactory;
CRegisteredClassFactory<CFooChildClass> mFooChildClassFactory;
};
static RegistrationData StaticRegistrationData;
// and here are the base class and the child class
// in the implementation of CBaseClass::Create I check, whether it should be overridden by another class.
class CBaseClass
{
public:
static CBaseClass* Create()
{
CRegisteredClasses* pRegisteredClasses = StaticRegistrationData.GetRegisteredClasses();
if (pRegisteredClasses->find("CBaseClass"))
{
CRegisteredClassFactory<CBaseClass>* pFac =
dynamic_cast<CRegisteredClassFactory<CBaseClass>* >(pRegisteredClasses->GetFactory("CBaseClass"));
mpInstance = pFac->CreateAndGet();
}
else
{
mpInstance = new CBaseClass;
}
return mpInstance;
}
virtual void Print(){cout << "Base" << endl;};
private:
static CBaseClass* mpInstance;
};
class CChildClass : public CBaseClass
{
public:
void Print(){cout << "Child" << endl;};
private:
};
Using this implementation, when I am doing this from some other class:
StaticRegistrationData.RegisterAll();
CBaseClass* b = CBaseClass::Create();
b.Print();
I expect to get "Child" in the output.
What do you think of this design? Did I complicate things too much and it can be done easier? And is it OK that I create a template that inherits from an abstract class?
I had to use dynamic_pointer (didn't compile otherwise) - is it a hint that something is wrong?
Thank you.
This sort of pattern is fairly common. I'm not a C++ expert but in Java you see this everywhere. The dynamic cast appears to be necessary because the compiler can't tell what kind of factory you've stored in the map. To my knowledge there isn't much you can do about that with the current design. It would help to know how these objects are meant to be used. Let me give you an example of how a similar task is accomplished in Java's database library (JDBC):
The system has a DriverManager which knows about JDBC drivers. The drivers have to be registered somehow (the details aren't important); once registered whenever you ask for a database connection you get a Connection object. Normally this object will be an OracleConnection or an MSSQLConnection or something similar, but the client code only sees "Connection". To get a Statement object you say connection.prepareStatement, which returns an object of type PreparedStatement; except that it's really an OraclePreparedStatement or MSSQLPreparedStatement. This is transparent to the client because the factory for Statements is in the Connection, and the factory for Connections is in the DriverManager.
If your classes are similarly related you may want to have a function that returns a specific type of class, much like DriverManager's getConnection method returns a Connection. No casting required.
The other approach you may want to consider is using a factory that has a factory-method for each specific class you need. Then you only need one factory-factory to get an instance of the Factory. Sample (sorry if this isn't proper C++):
class CClassFactory
{
public:
virtual CBaseClass* CreateBase() { return new CBaseClass(); }
virtual CFooBaseClass* CreateFoo() { return new CFooBaseClass();}
}
class CAImplClassFactory : public CClassFactory
{
public:
virtual CBaseClass* CreateBase() { return new CAImplBaseClass(); }
virtual CFooBaseClass* CreateFoo() { return new CAImplFooBaseClass();}
}
class CBImplClassFactory : public CClassFactory // only overrides one method
{
public:
virtual CBaseClass* CreateBase() { return new CBImplBaseClass(); }
}
As for the other comments criticizing the use of inheritance: in my opinion there is no difference between an interface and public inheritance; so go ahead and use classes instead of interfaces wherever it makes sense. Pure Interfaces may be more flexible in the long run but maybe not. Without more details about your class hierarchy it's impossible to say.
Usually, base class/ derived class pattern is used when you have an interface in base class, and that interface is implemented in derived class (IS-A relationship). In your case, the base class does not seem to have any connection with derived class - it may as well be void*.
If there is no connection between base class and derived class, why do you use inheritance? What is the benefit of having a factory if factory's output cannot be used in a general way? You have
class CAbstractFactory
{
public:
virtual ~CAbstractFactory()=0;
};
This is perfectly wrong. A factory has to manufacture something that can be used immediately:
class CAbstractFactory
{
public:
virtual ~CAbstractFactory(){};
public:
CBaseClass* CreateAndGet()
{
pClass = new Class;
return pClass;
}
private:
CBaseClass* pClass;
protected:
CBaseClass *create() = 0;
};
In general, you're mixing inheritance, virtual functions and templates the way they should not be mixed.
Without having read all of the code or gone into the details, it seems like you should've done the following:
make b of type CChildClass,
make CBaseClass::Print a virtual function.
Maybe I'm wrong but I didn't find any return statement in your CBaseClass::Create() method!
Personally, I think this design overuses inheritance.
"I am trying to create a system in which I can derive a Child class from any Base class, and its implementation should replace the implementation of the base class." - I don't know that IS-A relationships should be that flexible.
I wonder if you'd be better off using interfaces (pure virtual classes in C++) and mixin behavior. If I were writing it in Java I'd do this:
public interface Foo
{
void doSomething();
}
public class MixinDemo implements Foo
{
private Foo mixin;
public MixinDemo(Foo f)
{
this.mixin = f;
}
public void doSomething() { this.mixin.doSomething(); }
}
Now I can change the behavior as needed by changing the Foo implementation that I pass to the MixinDemo.