Design problem with Shared object loader - c++

I have been developing this class for loading plugins in the form of shared objects for an application. I currently have thought of 2 ways of loading the file names of all the plugins to be loaded by the app. I have written an interface for loading file names. I have a few questions about how to improve this design. Please help. Thanks.
EDIT: Code change per feedback :D.
#include "Plugin.h"
//This class is an interface for loading the list of file names of shared objects.
//Could be by loading all filienames in a dir, or by loading filenames specified in a file.
class FileNameLoader
{
public:
virtual std::list<std::string>& LoadFileNames() = 0;
};
class PluginLoader
{
public:
explicit PluginLoader(LoadingMethod, const std::string& = "");
virtual ~PluginLoader();
virtual bool Load();
virtual bool LoadPlugins(FileNameLoader&);
virtual bool LoadFunctions();
protected:
private:
explicit PluginLoader(const PluginLoader&);
PluginLoader& operator=(const PluginLoader&);
bool LoadSharedObjects();
list<std::string> l_FileNames;
list<PluginFunction*> l_Functions;
list<Plugin*> l_Plugins;
};
Anything that seems ugly still? Thanks for the feedback anyway.

It looks to me like you have your functionality spread across the enum, FileNameLoader, and the PluginLoader classes.
My suggestion would be to make a PluginLoaderByFile class, and a PluginLoaderByDir class - possibly with one inheriting from another, or possibly with a common base class. This way you can define other subclasses including the necessary additional code, and keep it encapsulated, if necessary, down the track.
This also makes it easier to use e.g. the factory or builder patterns in future.

You created a fine interface, but then you don't use it. And you then store the file names in a private member l_FileNames.
I would change the PluginLoader constructor to accept a FileNameLoader reference and use that reference to load file names. This way you won't need the LoadingMethod in the PluginLoader class.
Write two classes that implement the FileNameLoader interface, one for each loading method.
edit:
class FileNameLoader
{
public:
//RVO will work right? :D
virtual std::list<std::string>& LoadFileNames() = 0;
};
class FileNameLoaderByFile : public FileNameLoader
{
public:
std::list<std::string>& LoadFileNames()
{
// ...
}
}
class FileNameLoaderByDirectory : public FileNameLoader
{
public:
std::list<std::string>& LoadFileNames()
{
// ...
}
}
class PluginLoader
{
public:
explicit PluginLoader(FileNameLoader& loader)
{
fileNames = loader.LoadFileNames()
}
virtual ~PluginLoader();
private:
list<std::string> fileNames;
};

As for your statement of the current problem.
U can use either
vector for params or
since u are using a string u can as well parse it using some delimiter (say " ", ",")
However I wouldn't let the params or method of loading be visible in the PluginLoader.
Instead would use a common/generic interface.

Related

C++: implementing multiple instances of an interface or an optional interface in a class

I'm having trouble finding best practice information about what I believe should be a fairly common problem pattern.
I will start with a specific (software update related) example, because it makes the discussion more concrete, but the issue should be fairly generic.
Say that I have a software updater interface:
struct Software_updater {
virtual ~Software_updater() = default;
virtual void action1(const Input1& input1) = 0;
virtual void action2() = 0;
virtual bool action3(const Input2& input2) = 0;
virtual Data1 info1() = 0;
virtual Data2 info2() = 0;
// etc.
};
For my first implementation A, I am lucky, everything is straightforward.
class A_software_updater : public Software_updater {
// ...
};
A B_software_updater, however, is more complicated. Like in the A-case, it is connected to the target to update in a non-trivial manner and maintains a target connection state. But more importantly, it can update two images: the application image, and the boot loader image.
Liking what I have so far, I see no real reason to go for a refactoring, so I assume I can just build upon it. I come up with the following solution:
class B_software_updater {
public:
Software_updater& application_updater() { return application_updater_; }
Software_updater& boot_loader_updater() { return boot_loader_updater_; }
private:
class Application_updater : public Software_updater {
// ...
} application_updater_;
class Boot_loader_updater : public Software_updater {
// ...
} boot_loader_updater_;
};
I.e. I am returning non-const references to "interfaces to" member variables. Note that they cannot be const, since they mute state.
Request 1: I think the solution above is a clean one, but I would be happy to get some confirmation.
In fact, I have recently faced the issue of having to optionally provide an interface in a class, based on compile-time selection of a feature, and I believe the pattern above is a solution for that problem too:
struct Optional_interface {
virtual ~Optional_interface() = default;
virtual void action1(const Input1& input1) = 0;
virtual void action2() = 0;
virtual bool action3(const Input2& input2) = 0;
virtual Data1 info1() = 0;
virtual Data2 info2() = 0;
// etc.
};
class A_implementation {
public:
#ifdef OPTIONAL_FEATURE
Optional_interface& optional_interface() { return optional_implementation_; }
#endif
// ...
private:
#ifdef OPTIONAL_FEATURE
class Optional_implementation : public Optional_interface {
// ...
} optional_implementation_;
#endif
// ...
};
Request 2: I could not find a simple (as in: not unnecessarily complicated template-based) and clean way to express a compile-time optional inheritance at the A_implementation-level. Can you?
Better solution
Based on a comment from #ALX23z about invalidation of member variable reference upon move, I am now rejecting my initial solution (original post). That invalidation problem would not be an issue for my case, but I am in search of a generic pattern.
As usual, the solution is obvious once one has found it.
First a summary of my initial problem.
Say that I have a software updater interface (or any interface, this is just an example):
struct Software_updater {
virtual ~Software_updater() = default;
virtual void action1(const Input1& input1) = 0;
virtual void action2() = 0;
virtual bool action3(const Input2& input2) = 0;
virtual Data1 info1() = 0;
virtual Data2 info2() = 0;
// etc.
};
A B_software_updater can update two images: an application image, and a boot loader image. Therefore, it wants to provide two instances of the Software_updater interface.
A solution that is better than the one in my original post is to declare a B_application_updater and a B_boot_loader_updater, constructed from a B_software_updater&, outside of B_software_updater, and instantiated by client code.
class B_application_updater : public Software_updater {
B_application_updater(B_software_updater&);
// ...
};
class B_boot_loader_updater : public Software_updater {
B_application_updater(B_boot_loader_updater&);
// ...
};
It does have the drawback of forcing the client code to create three objects instead of only one, but I think that the cleanliness outweighs that drawback.
This will work for the optional interface too (see original post):
class A_optional_implementation : public Optional_interface {
A_optional_implementation(A_implementation&);
};
A_optional_implementation will be declared outside of A_implementation.
Applications that do not need that interface will simply not instantiate A_optional_implementation.
Additional thoughts
This is an application of the adapter design pattern!
Basically, what this answer comes down to:
An Interface class.
An Implementation class that does the job, but does not really care about the interface. It does not inherit Interface. The point of this is that Implementation could "do the job" corresponding to several interfaces, without the complexity and drawbacks of multiple inheritance (name conflicts, etc.). It could also do the job corresponding to several instances of the same interface (my case above).
An Interface_adapter class that takes an Implementation& parameter in its constructor. It inherits Interface, i.e. it effectively implements it, and that is its only purpose.
Taking a step back, I realize that this is simply an application of the adapter pattern (although Implementationin this case does not necessarily need to implement any externally defined interface - its interface is just its public member functions)!
An intermediate solution: leave the adapter classes inside the implementation class
In the solution above, I specify that the adapter classes are declared outside of the implementation classes. While this seems logical for the traditional adapter pattern case, for my case, I could just as well declare them inside the implementation class (like I did in the original post) and make them public. The client code would still have to create the implementation and adapter objects, but the adapter classes would belong to the implementation namespace, which would look nicer.

Make POD from class with virtual members

I have two classes: Parent and Derived. I want to achieve ability to save and read them from/to binary file, or transfer them. Please help with idea or code snippets how do it.
class Parent {
public:
virtual int func1(){ return 1; }
virtual unsigned func2() = 0;
std::string asd;
}
class Derived : public Parent {
public:
unsigned func2(){ return 2; }
bool boo;
}
Save to binary file
Parent *obj = new Derived;
write_to_file( obj, sizeof(*obj) );
Then read from file
read_from_file( obj, sizeof(*obj) );
But this method will overwrite pointers to virtual functions. So I need to create POD class without virtuals to save it and to read from file. Right? Create reflected POD class for every Derived seems not good idea.
There is no direct answer to this question. You should use serialization. C++ has no native serializers, as Java or C#. But there are a lot of open-source serializers over the internet. For example boost::serialization, s11n, and many others.

reading message structure from a text file and generate a class based on the it

I have a question. Is it possible for cpp/qt language to do the following ?
1) Read from a text file e.g. template.txt
struct messageA
{
variableA int 0
variableB string abc
variableC double 1.0
}
struct msgB
{
variableD int 0
variableE byte 255
variableF unsignedInt 123
} //... and so on
2) Based on the details from the template.txt, generate a class that will create the variables and the datatype accordingly?
I have a general idea on how to read the the content from the text file and stores the details but I'm having problem to come up with an idea on how to have create the class based on the data I've received.
any tips/hints would be great! thanks !
As user3755692 already mentioned, you can't create classes on runtime. But if you really desperate about idea of dynamically creation of some objects with different fields and methods, you can try a component-based design. It's really effective, but sometimes hard to implement, approach.
It's like you have a dummy object, which is just a container of components, like so:
class BaseObject
{
public:
void addComponent(IComponent* component);
Icomponent* getComponent();
void executeComponent(int id);
void updateAllComponents();
private:
vector<IComponent*> _components;
};
And you have various components inherited from IComponent interface(which provides some basic functionality and pure virtual methods), which you can add to your base object.
Components can be anything:
// Component that stores int value
class IntComponent : public IComponent
{
public:
// This is something inherited from IComponent
virtual void init()
{
integerValue = 0;
}
public:
int integerValue;
};
// Component that allows you to print something in console
class PrintingComponent : public IComponent
{
public:
// This is something inherited from IComponent
virtual void init()
{
}
public:
void print(const char* phrase)
{
cout<<phrase<<endl;
}
};
You can combine different components in your base object to achieve deserved functionality. And you can create such objects using a some kind of configuration file. Like simple *.txt file:
[OBJECT]
COMPONENT_INT,
COMPONENT_PRINT
[OBJECT]
COMPONENT_INT,
COMPONENT_FILEREADER
Then you will parse it and create two objects with different sets of components, which then can be used inside of your program.
Here's some useful articles about this approach:
1)http://www.randygaul.net/2013/05/20/component-based-engine-design/
2)http://gameprogrammingpatterns.com/component.html
3)Component based game engine design - much useful links here too
Those articles above focused on gamedev mainly, but there's a very good explanations.
Good luck!
It's not like in python where you can create classes on runtime; c++ is a compiled language. You can create a source file from reading the file and compile it. Such a technologie is also used by Qt's moc creator. If you then want to include your class in your running environment, you can build a shared library with your class and load the library. Also thee this question.

C++ How can achieve this Interface configuration?

I certainly don't know how to title this question, sorry.
I'm having some problems to design the following system.
I need a class which will make some work, but this work can be done in a bunch of different ways, say that this work will be made through "drivers".
These drivers can have different interfaces and because of that I need to build a wrapper for each driver.
So I got (or I need) this:
Me ---> MainClass ----> Wrapper ----> Drivers
MainClass is the class I will touch and will call the drivers methods through different wrappers.
Here an example of usage:
MainClass worker;
worker.set_driver("driver_0");
worker.start_process(); //Start process calls a wrapper method which calls a driver's method.
To achieve this I made an interface class:
class Driver_Interface : public QObject
{
Q_OBJECT
public:
Driver_Interface(QObject* parent=0) : QObject(parent){}
virtual bool open()=0;
virtual bool close()=0;
virtual bool write()=0;
virtual bool set_config()=0;
};
A driver wrapper has this shape:
class Driver0 : public Driver_Interface
{
Q_OBJECT
public:
Driver0( QObject* parent=0);
Driver0();
bool open();
bool close();
bool write();
bool set_config();
};
Finally here comes the conflicting point, defining the MainClass:
I would like to avoid to create one member for each wrapper, so I tried this, and right now compiler doesn't complains:
class MainClass
{
public:
MainClass();
~MainClass();
void init();
void set_driver( const QString& );
void start_process();
protected:
QString driver_str;
Driver_Interface* driver; //!<--- Here Here!!!
};
When setting the driver chosen, I do this:
if( driver_str.compare("driver_0")==0 )
this->driver = new Driver_0();
Is this a valid C++ configuration or will I have problems sooner or later?
Basically, what worries me is the creation of the driver of a different type from Driver_Interface, I'm seeing that it casts automatically and no one complains...
Actually I have some problems now compiling, the infamous vtables not defined in Driver_0... does this have some relation with what I want to achieve? UPDATED: I fixed this by deleting the *Driver_Interface* constructor.
To me your basic idea seems to be fine. I would consider separating the creation of drivers into a factory (or at least a factory method) though.
This seems reasonable to me. Having a FactoryMethod or class (AbstractFactory) that creates an object of the required concrete subclass based on some config value is a common pattern.
You could consider having the MainClass implement something like
DriverInterface* createDriver(const string& driverType)
instead of encapsulating the resulting concrete DriverInterface subclass in MainClass. But if you only ever want one concrete DriverInterface instance, the above looks fine.
I would pass "driver_0" to the constructor, and call MainClass::set_driver from there. You can then make MainClass::set_driver private unless you need to change drivers.

calling a function from a set of overloads depending on the dynamic type of an object

I feel like the answer to this question is really simple, but I really am having trouble finding it. So here goes:
Suppose you have the following classes:
class Base;
class Child : public Base;
class Displayer
{
public:
Displayer(Base* element);
Displayer(Child* element);
}
Additionally, I have a Base* object which might point to either an instance of the class Base or an instance of the class Child.
Now I want to create a Displayer based on the element pointed to by object, however, I want to pick the right version of the constructor. As I currently have it, this would accomplish just that (I am being a bit fuzzy with my C++ here, but I think this the clearest way)
object->createDisplayer();
virtual void Base::createDisplayer()
{
new Displayer(this);
}
virtual void Child::createDisplayer()
{
new Displayer(this);
}
This works, however, there is a problem with this:
Base and Child are part of the application system, while Displayer is part of the GUI system. I want to build the GUI system independently of the Application system, so that it is easy to replace the GUI. This means that Base and Child should not know about Displayer. However, I do not know how I can achieve this without letting the Application classes know about the GUI.
Am I missing something very obvious or am I trying something that is not possible?
Edit: I missed a part of the problem in my original question. This is all happening quite deep in the GUI code, providing functionality that is unique to this one GUI. This means that I want the Base and Child classes not to know about the call at all - not just hide from them to what the call is
It seems a classic scenario for double dispatch. The only way to avoid the double dispatch is switching over types (if( typeid(*object) == typeid(base) ) ...) which you should avoid.
What you can do is to make the callback mechanism generic, so that the application doesn't have to know of the GUI:
class app_callback {
public:
// sprinkle const where appropriate...
virtual void call(base&) = 0;
virtual void call(derived&) = 0;
};
class Base {
public:
virtual void call_me_back(app_callback& cb) {cb.call(*this);}
};
class Child : public Base {
public:
virtual void call_me_back(app_callback& cb) {cb.call(*this);}
};
You could then use this machinery like this:
class display_callback : public app_callback {
public:
// sprinkle const where appropriate...
virtual void call(base& obj) { displayer = new Displayer(obj); }
virtual void call(derived& obj) { displayer = new Displayer(obj); }
Displayer* displayer;
};
Displayer* create_displayer(Base& obj)
{
display_callback dcb;
obj.call_me_back(dcb);
return dcb.displayer;
}
You will have to have one app_callback::call() function for each class in the hierarchy and you will have to add one to each callback every time you add a class to the hierarchy.
Since in your case calling with just a base& is possible, too, the compiler won't throw an error when you forget to overload one of these functions in a callback class. It will simply call the one taking a base&. That's bad.
If you want, you could move the identical code of call_me_back() for each class into a privately inherited class template using the CRTP. But if you just have half a dozen classes it doesn't really add all that much clarity and it requires readers to understand the CRTP.
Have the application set a factory interface on the system code. Here's a hacked up way to do this. Obviously, apply this changes to your own preferences and coding standards. In some places, I'm inlining the functions in the class declaration - only for brevity.
// PLATFORM CODE
// platformcode.h - BEGIN
class IDisplayer;
class IDisplayFactory
{
virtual IDisplayer* CreateDisplayer(Base* pBase) = 0;
virtual IDisplayer* CreateDisplayer(Child* pBase) = 0;
};
namespace SystemDisplayerFactory
{
static IDisplayFactory* s_pFactory;
SetFactory(IDisplayFactory* pFactory)
{
s_pFactory = pFactory;
}
IDisplayFactory* GetFactory()
{
return s_pFactory;
}
};
// platformcode.h - end
// Base.cpp and Child.cpp implement the "CreateDisplayer" methods as follows
void Base::CreateDisplayer()
{
IDisplayer* pDisplayer = SystemDisplayerFactory::GetFactory()->CreateDisplayer(this);
}
void Child::CreateDisplayer()
{
IDisplayer* pDisplayer = SystemDisplayerFactory::GetFactory()->CreateDisplayer(this);
}
// In your application code, do this:
#include "platformcode.h"
class CDiplayerFactory : public IDisplayerFactory
{
IDisplayer* CreateDisplayer(Base* pBase)
{
return new Displayer(pBase);
}
IDisplayer* CreateDisplayer(Child* pChild)
{
return new Displayer(pChild);
}
}
Then somewhere early in app initialization (main or WinMain), say the following:
CDisplayerFactory* pFactory = new CDisplayerFactory();
SystemDisplayFactory::SetFactory(pFactory);
This will keep your platform code from having to know the messy details of what a "displayer" is, and you can implement mock versions of IDisplayer later to test Base and Child independently of the rendering system.
Also, IDisplayer (methods not shown) becomes an interface declaration exposed by the platform code. Your implementation of "Displayer" is a class (in your app code) that inherits from IDisplayer.