DLL-based application framework with bi-directional interfaces (Windows) - c++

Solved
this wasn't the problem, since it's being implicitly cast to IFramework anyway.
I was concerned it may have to do with my methods not returning HRESULT, or with my stubby implementations of IUnknown::QueryInterface, but the real problem was merely a compiler setting that had overridden several macros I needed for common calling conventions (perhaps I should have included them in the question). This had corrupted the stack.
It's interesting though, that it worked will all compilers I tested, even without implementing IUnknown at all - a little research suggests that all serious Windows compilers handle abstract C++ interfaces the same way - namely as a virtual table specifically to be used as a COM interface.
Hi. I'm trying to create an extensible application framework. My basic concept is this:
The "Framework" box will build an .exe whereas the multiple "Plugin" boxes will build .dll files.
However, my implementation is apparently flawed. I have an idea what's the problem, but I'm running out of workarounds. I've done it exactly like this with .NET projects, but the problem I have now didn't apply to the C# environment.
Consider these interfaces:
class IFramework
{
public:
virtual void FrameworkMethod() = 0;
};
class IPlugin
{
public:
virtual void PluginMethod() = 0;
virtual void PluginCallbackTest() = 0;
virtual void SetFramework(IFramework *framework) = 0;
};
Implementation of the framework:
class CFramework : IFramework
{
public:
void FrameworkMethod(); // printf("FrameworkMethod");
void DoSomething(); // this is the testbench basically, see below
};
And the implementation of the plugin:
class CPlugin : public IPlugin
{
IFramework *Framework;
public:
void PluginMethod(); // printf("PluginMethod");
void PluginCallbackTest(); // Framework->FrameworkMethod();
void SetFramework(IFramework *framework); // Framework = framework;
};
// plugin factory -> COM interface
extern "C" PLUGIN_API IPlugin *GetPlugin(); // return new CPlugin;
Now to demonstrate that this concept doesn't work:
void CFramework::DoSomething()
{
HMODULE PluginHandle = LoadLibrary(...); // explicit linking
auto GetPlugin = ((IPlugin *)(*)())GetProcAddress(...);
IPlugin *plugin = GetPlugin();
plugin->PluginMethod();
// up until here everything's perfectly COM-compliant and works super
plugin->SetFramework(this); // <-- that is the problem
plugin->PluginCallbackTest(); // <-- runtime crash if compiler differs
FreeLibrary(PluginHandle);
}
The problem is that the SetFramework(this) doesn't work like COM. It's not that it just feels wrong to write it like this - I can't implement a working plugin with a compiler that differs from the one I used to build CFramework (runtime crashes).

If you want to allow different compilers for the plug-ins from what you use for the app then you need to use COM exclusively across the boundary between app and plug-ins. That is precisely the problem that COM was designed to solve.

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.

porting C++ library to .NET

I have this simple library written in C++ (source code included)
struct MyStruct
{
char message[ 90 ];
int t;
};
enum MyEnum
{
MY_ENUM_1, MY_ENUM_2
};
class IEvent
{
public:
virtual ~IEvent() {}
virtual void event1( time_t ) = 0;
virtual void event2( MyStruct s ) = 0;
virtual void event3( MyEnum e ) = 0;
};
class Impl;
class MY_API Controller
{
public:
Controller( IEvent* eventListener );
~Controller();
void addListener( IEvent* eventListener );
void removeListener( IEvent* eventListener );
void f1( MyEnum e );
void f2();
private:
Impl* mImpl;
};
The code is implemented in C++11. I need to port this code to .NET.
I thought that a good choice can be C++/CLI but after lots of google I didn't find nothing.
Does someone know how to port this code in C++/CLI? I am able to build all the library in C++/CLI but the library doesn't export any symbols.
Edit1
The library is huge and a re-write in other language is too expensive.
If you want to port this code to .NET, to be used in other .NET languages, such as C#, then you're going to want to re-work how this library does things. Regardless of what language you choose to implement in, if your goal is to be consumed by other .NET languages, you should switch to the .NET paradigms.
For example: currently, you have an abstract class named IEvent. You could create a .NET interface named IEvent, and implement it the same way, but that's not how you do things in .NET. Instead, you'd want to define 3 delegate types, and have your Controller class define 3 events of those delegate types. Instead of addListener and removeListener, each of the events would have add and remove methods (accessed through += and -=).
delegate void Event1Handler(object sender, DateTime data);
delegate void Event2Handler(object sender, MyStruct data);
delegate void Event3Handler(object sender, MyEnum data);
public class EventExample_Controller
{
public event Event1Handler Event1;
public event Event2Handler Event2;
public event Event3Handler Event3;
}
As for the language to use, my initial response would be "C# if you can, C++/CLI if you have to". You haven't said what this library does, it may not be easy, or even possible, to do it in C#. But if you can do it in C#, then you'll get the benefits that language provides: Many of the benefits have equivalents in C++/CLI (e.g., linq query syntax can be represented with regular syntax, extension methods can be called as regular static methods, everything using the async keyword can be done with Tasks and a crapload of state variables), but some are C# only (e.g., having one assembly that works in 32-bit and 64-bit mode).
As for your try to compile the library as-is in C++/CLI, you need to mark the classes as managed classes. Change the classes to public ref class, and the enums to public enum class, and that'll create them as managed. Your next step will be to switch all your pointers to your own classes from unmanaged pointers (*) to managed references (^), and use gcnew instead of new for them.

Hiding multiple implementations behind a single interface

I know about the Strategy and Abstract Factory design patterns - however they don't solve my current problem:
I'm creating a C++ library that offers a very basic GUI. However I want the user to be able to choose at compile time which GUI library to use (say Qt or FLTK) to actually render the GUI. The user should however only need to know about the methods in my library.
It should be possible to compile the same code without any changes using either a Qt backend or an FLTK backend.
I thought of something like:
class A
{
// do things that are not specific to QT or FLTK here as there are many
// methods I will need independent of the backend
}
class QT_A : public A
{
// Implement the actual creation of a window, display of a widget here using Qt
}
class FLTK_A : public A
{
// Implement the actual creation of a window, display of a widget here using FLTK
}
The problem is that I do not want the user to know about QT_A or FLTK_A. The user (developer) should just deal with A. Also, I can't have both variants at the same time as I don't want my library to depend on both Qt and FLTK; just whichever was chosen at compile time.
One option is the Pimpl idiom described in another answer.
Another option is a factory returning a pointer to the interface class:
std::unique_ptr<A> make_A()
{
#if defined(USING_QT)
return std::unique_ptr<A>(new QT_A(...));
#elif defined(USING_FLTK)
return std::unique_ptr<A>(new FLTK_A(...));
#else
#error "No GUI library chosen"
#endif
}
The Pimpl idiom may be an alternative. It allows you to create a common interface without framework dependent members.
class A
{
struct impl;
std::unique_ptr<impl> pimpl; // or scoped_ptr/auto_ptr on non-C++11
public:
A();
~A();
void do_sth();
};
Then, the source file can provide different implementations of impl depending on the backend.
#ifdef QT
struct A::impl : QWidget { // Make it polymorphic, if you need
QImage img;
QString data;
};
void A::do_sth()
{
impl->make_it(); // full access to the Qt things
}
A::A()
: pimpl(new ...)
{
}
A::~A() {} // no need for delete thanks the smart pointer
#endif
No need of fancy patterns.
You distribute
headers of A;
a library that contains A, QT_A, and make_A function;
another library that contains A, FLTK_A and another implementation of make_A function.
The user links to either library.

QtPlugins implementing multiple interfaces and casting to a common interface

I have a set of interfaces that can be implemented by plug-ins in a Qt
application. Every plug-in must implement at least one common
interface, called Base_plugin, to provide some basics (description,
name, etc.). When calling a specific plug-in interface I often have to
get this basic to present it in the user interface. This leads to a
lot of code like:
Foo_plugin* p = getSuitableFooPlugin();
// cannot use qobject_cast, plug-in interfaces don't derive QObjects
Base_plugin* b = dynamic_cast<Foo_plugin*>(p);
setName(b->name());
p->getAction();
This works at least on gcc, but I'm afraid that this is not going to
work on Windows. Alternatively I could use reinterpret_cast or store
pointers of the correct type to each plug-in when loading them (I have
a valid QObject* there). Neither of those solutions seems really
clean to me.
Is there a better way around this problem?
As I understand, you have smth like this (if you don't, think about refactor to make it like this)
struct IBase
{
virtual QString name() const = 0;
virtual void setName(const QString name&) = 0;
};
Q_DECLARE_INTERFACE(IBase, "best.app.ever.plugins.base");
struct IFoo
{
virtual void foo() = 0;
};
Q_DECALRE_INTERFACE(IFoo, "best.app.ever.plugins.foo" );
struct Plugin: QObject, IBase, IFoo
{
Q_OBJECT()
Q_INTERFACES(IBase)
Q_INTERFACES(IFoo);
//....
};
Q_EXPORT_PLUGIN2(best_app_ever, Plugin);
now when you load plugin, you get an QObject and you shoud use qobject_cast to cast this QObject to your interface classes.
Specializations of qobject_cast that process casting to your interfaces get created automatically by Q_DECLARE_INTERFACE macroses.
Perhaps I'm not getting it right, but can't you just write:
Foo_plugin* p = getSuitableFooPlugin();
setName(p->name());
p->getAction();
Since Foo_plugin inherits from Base_plugin, and if Base_plugin::name() is public, you can call it without casting.

SWIG C++ bindings with callback

I am writing some SWIG/Python bindings for some C++ code. This is for what is called the Kinect Accidental API, I have the motor and led functions working. The callbacks to the Listener class which parse and populate the RGB and Depth buffers do not seem to get called from SWIG. The data capture threads evidently start up and start hogging the CPU, but no debug lines from the callback come through. What would be better way to populate data buffers and easily access them from python ?
class KinectListener
{
public:
virtual ~KinectListener(){};
virtual void KinectDisconnected(Kinect *K) {};
virtual void DepthReceived(Kinect *K) {};
virtual void ColorReceived(Kinect *K) {};
virtual void AudioReceived(Kinect *K) {};
};
Here is the listener class with the virtual methods, can the Python wrapped version of this class be used to inherit listeners for the c++ class ? I added a minimal listener in C++ and now the remaining work is to access the arrays efficiently with typemaps. Currently I am using this naive typemap
%typemap(out) unsigned short [ANY] {
int i;
$result = PyList_New($1_dim0);
for (i = 0; i < $1_dim0; i++) {
PyObject *o = PyInt_FromLong((long)$1[i]);
PyList_SetItem($result,i,o);
}
}
Better options ?
There is a way using the directors feature.
Enable it for your KinectListener proxy, one line of code :
%feature("director") KinectListener
Then you can inherit from KinectListener class in python code and define your functions.
By coincidence, I happen to be looking into callbacks with SWIG at the moment.
The SWIG 2.0 documentation says this:
SWIG provides full support for function pointers provided that the callback functions are defined in C and not in the target language. ... However, existing C functions can be used as arguments provided you install them as constants. One way to do this is to use the %constant directive like this ...
I'm planning to write a C callback with hand-written JNI to call into Java. If there's another way, I would also love to hear it.