SWIG C++ bindings with callback - c++

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.

Related

Is there any way to convert a superclass pointer to subclass pointer by subclass name in c++ string?

Recently, I'm working on something like reflection in c++ using by my plugin system. Right now, I wonder if I can convert a super-class pointer into sub-class pointer given the string name of sub-class:
class SuperClass
{
public:
SuperClass(const string &name):class_name(name){}
// a convert function like
// return value should variant like SubClassA * or SubClassB *
// SubClassA * ConvertByName();
private:
string class_name;
};
class SubClassA: public SuperClass
{
public:
SubClassA():SuperClass("SubClassA")
};
class SubClassB: public SuperClass
{
public:
SubClassB():SuperClass("SubClassB")
}
when using:
// some place create instance
SuperClass *one = new SubClassAï¼›
SuperClass *two = new SubClassB;
// other place using
auto a = one->ConvertByName(); // a is of type SubClassA
auto b = two->ConvertByName(); // b is of type SubClassB
Can it be realized? Or is there any better way in c++?
[Update 1]
There my be some other sub-classes, such as, SubClassC, SubClassD, ...
So basically, we don't know what and how many sub-classes are derived from this SuperClass. What we know about sub-class is only its class name in string format.
[Update 2]
My motivation
I need this for plugin system. I want to create a plugin anytime, but don't want hack into my plugin core system codes. That is plugin codes are isolated from projects. A plugin system will never know what and how many plugins are added into system until runtime
Possible, well, this way you manually somewhat reimplement dynamic dispatch and make your class a kind of sealed.
struct Base {
Base(std::string type_id): type_id(std::move(type_id)) {}
template<class F> auto visitThis(F &&f) const;
template<class F> auto visitThis(F &&f);
private:
std::string type_id;
};
struct Child1: Base { Child1(): Base("Child1") {}};
struct Child2: Base { Child2(): Base("Child2") {}};
template<class F> auto Base::visitThis(F &&f) const {
if(type_id == "Child1") {
return std::invoke(std::forward<F>(f),
static_cast<Child1 const *>(this));
}
else if(type_id == "Child2") {
return std::invoke(std::forward<F>(f),
static_cast<Child2 const *>(this));
}
else throw std::runtime_error("Unsupported subclass");
}
template<class F> auto Base::visitThis(F &&f) {
if(type_id == "Child1") {
return std::invoke(std::forward<F>(f), static_cast<Child1 *>(this));
}
else if(type_id == "Child2") {
return std::invoke(std::forward<F>(f), static_cast<Child2 *>(this));
}
else throw std::runtime_error("Unsupported subclass");
}
int main() {
std::unique_ptr<Base> b1 = std::make_unique<Child1>();
b1->visitThis([](Child1 const *ch) { std::cout << "Hi, Ch1!\n"; });
}
If your classes all have some virtual thing, consider using dynamic_cast
See this C++ reference for details, and read a good C++ programming book.
Read also the documentation of your C++ compiler (e.g. GCC)
Right now, I wonder if I can convert a super-class pointer into sub-class pointer given the string name of sub-class
This is not possible without specific coding and programming conventions
(since the class names do not exist at runtime). Look inside Qt or RefPerSys as an example.
A possible approach could be to write your C++ code generator to help you (so generate parts of your C++ code - probably some header file containing your class declarations-, like Qt does with its moc, and configure your build automation tool, e.g. your Makefile). Look perhaps inside ANTLR, SWIG, GPP, etc...
A more ambitious approach, if you use GCC, would be to write your own GCC plugin. Consider also extending Clang. This is worthwhile only for large existing code bases.
A plugin system will never know what and how many plugins are added into system until runtime
It seems that you are designing some plugin machinery. Take inspiration from Qt plugins or FLTK plugins. If on Linux, see manydl.c and consider generating some of the C++ code of your plugins (see e.g. this draft report, and the CHARIOT and DECODER European projects).
BTW, do you want to unload plugins (on Linux, call dlclose(3); read also then the C++ dlopen minihowto)? Do you have a multi-threaded application? If you do, you'll better have some locking (e.g. std::mutex) to avoid parallel plugin loading.
You could also consider generating at runtime some glue code: e.g. using libgccjit or asmjit, or simply generating some temporary C++ code (e.g. on Linux in /tmp/generated.cc that you would compile - maybe with popen(3) - using g++ -Wall -O -fPIC /tmp/generated.cc -o /tmp/generated-plugin.so) and later dlopen(3) that /tmp/generated-plugin.so. Read Drepper's paper how to write shared libraries (for Linux).
C++ does not ship enough information in binaries to write new code.
Dynamically linked C++ code do not carry enough information for other dynamically linked code to build a copy of the class at link time.
So there is no way, short of shipping a C++ compiler, to do exactly what you are asking. I have heard of some people who go that far, and embed C++ compilers into their hand-grown "dynamic linking" environment, but usually by that point you are better off with using a language where that is a built-in feature, or not using the raw C++ object model and using something reflection-enabled.
It is quite likely that the underlying problem you are trying to solve using this technique can be solved in C++, if one exists.

Generic Objective-to-C++ translation strategy

I'd like to expose ObjC notification handlers to my C++ client code.
I'm doing it this way.
I wrapped an ObjC object (call it X) inside a C++ object.
X observes the notification and registers a callback (call it F).
F translates the ObjC structures from the notification into their C++ counterparts, calls a user-registered global C++ callback function (call it FF). The translated C++ structs become the input arguments of FF.
Now the problem is that the arguments' original ObjC structures are complex, containing multiple layers of ObjC objects that need to be translated.
On my side, the wrapper observer F needs to do nothing special, just calling the client's FF.
What is the more proper strategy of my translation at this point?
Should I:
Translate those structures down to the bottom-level of all their members so that I have equivalent C++ structures to use as the arguments, or,
Create a C++ class to wrap these arguments into one object and expose the class interface to user so they can use those C++-wrapped arguments in their C++ implementation, or,
Give up on the wrapping idea and ask user to code in ObjC and register their own observer functions directly?
My targeted users are iOS developers that may or may not be Android developers too.
You can mix c++ and objective-c++ in a .mm implementation file. This means you can give a c++ lambda (or block) to the objective-c++ class that references your c++ owner.
something like this:
implementation.mm:
#interface Shim : NSObject
{
std::function<void>() _notify;
}
#end
#implementation Shim
- void register_cpp(std::function<void>() f)
{
_notify = std::move(f);
}
- (void) my_handler()
{
if(_notify)
_notify();
}
#end
struct cpp_class::impl {
impl()
: _shim([Shim alloc[init]])
{
_shim.register_cpp(std::bind(&impl::callback, this));
}
private:
void callback() {
// do callback here;
}
Shim* _shim;
};
cpp_class::cpp_class()
: _impl(new impl)
{
}
cpp_class::~cpp_class()
{
delete _impl;
}
header.h:
struct cpp_class{
cpp_class();
~cpp_class();
private:
struct impl;
impl* _impl;
};
In reality you'll want to be careful to ensure that objects still exist when doing callbacks (argues for weak_ptr::lock(), enable_shared_from_this, etc.) since objective-c likes to put callbacks onto a thread's run loop (basically a queue) and that means your c++ object can go away before the callback arrives - but this code should give you the right idea.

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.

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.

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

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.