I want to generate C wrappers from C++ libraries.
There are tutorials on how to do it by hand:
http://dsc.sun.com/solaris/articles/mixing.html
http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html
But it is too much of a manual labor.
For example, for this:
struct RtAudio {
virtual DeviceInfo const& f() {...}
class DeviceInfo {
virtual void g() { ... }
};
...
};
I need to write:
struct RtAudioC {
RtAudio x;
};
struct DeviceInfo {
RtAudio::DeviceInfo x;
};
extern "C" {
RtAudioC* newRtAudio() {
return new RtAudioC;
}
void deleteRtAudio(RtAudioC *p {
delete p;
}
/* do something with RtAudio::f() */
void g(DeviceInfo *p) {
try {
p->x.g();
} catch (SomeError & err) {
}
}
}
Are there tools that can automate this process?
You can try SWIG, C code generator was last year's GSoC project. AFAIK they haven't merged it to the trunk yet, so you'd have to checkout & build the branch from SVN.
I just developed a C function wrapper in Python to do exactly this (generate C++ classes that wrap C functions).
It's still young but the bulk of what I needed it to do is in there now. Give it a try and let me know what you think: https://github.com/mlb5000/CFunctionWrapperGenerator
There is gmmproc which creates C++ wrappers for gobject based C libraries, but that's the only code generator I've heard of between C and C++.
If you're good with writing a parser, it wouldn't be too difficult a task to create a basic wrapper generator. In the end you might have to add a few finishing touches manually, but still your work load would be reduced.
How much of your C++ code is already written vs. how much has yet to be written?
If a reasonable proportion is to-be-written, I would create a simplified syntax, that generates both the C++ and C headers, like IDL does for COM interfaces. This simplified syntax will be much easier for you to parse than C++, or you can likely find something off the shelf that does this.
I don't know of an off-the-shelf tool to do this. If you want to automate the generation and are happy to write your own scripts, pygccxml (based on GCC-XML) is quite a nice way to parse C++ headers.
Related
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.
I have a third party library as source code. It comes with a Visual Studio project that builds a .lib from it.
I want to access the functionality from C# though, so I copied the project and changed it to create a dll.
The DLL didn't contain any exported functions though, so I also created a module definition (.def) file, and added the functions I need in the EXPORTS section.
This works for all the functions that are declared in extern "C" blocks. However, some of the functions that I need are declared outside of those blocks.
If I add those to the EXPORTS section I get the error LNK2001 unresolved external symbol XYZ :(
I don't want to change the sourcecode of the 3rd party library if I can avoid it.
What's the most elegant and hopefully simplest way to access those functions as well?
Edit
One more point for clarification: As far I can tell there is no C++ functionality involved in the interface I want to expose. I honestly don't understand why the 3rd party authors did not just include the few remaining functions into the extern "C" blocks. These functions are at the bottom of the header file, maybe the person that added them just made a mistake and put them outside of the extern "C" blocks scope.
For C++ one way (IMHO the most elegant) would be using C++/CLI, which is designed for that. Especially if you have not only functions but also classes.
You create a thin wrapper layer which is fairly simple:
Create a CLI class
put a member instance of the original class
wrap all public methods from the original class
Like This (untested):
C++ nativ:
// original c++ class
class Foo {
public:
Foo(int v) : m_value(v) {}
~Foo() {}
int value() { return m_value; }
void value(int v) { m_value = v; }
private:
int m_value;
};
CLI wrapper:
// C++/CLI wrapper
ref class FooWrap
{
public:
FooWrap(int v) { m_instance = new Foo(v); }
!FooWrap() { delete m_instance; }
~FooWrap() { this->!FooWrap(); }
property int value {
int get() { return m_instance->value(); }
void set(int v) { m_instance->value(v); }
}
private:
Foo *m_instance;
};
Here you can find a short howto, which describes it in more detail.
Edit:
From your comments:
[...] I never worked with C++/CLI though and the language looks a little confusing. Since the project deadline is pretty close I'm not sure if there's enough time to learn it. I'll definitely keep this option in mind though!
If you are not looking for the most elegant way, as in your original question, but for the fastest/shortest way: For C++ one way (IMHO the shortest way) would be using C++/CLI, which is designed for that. Especially if you have not only functions but also classes. You create a thin wrapper layer which is fairly simple... Here you can find a short (in 10 min) howto, which describes it in more detail.
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.
I'm currently writing an AI for a game that is written in c++. The AI is conceptually fairly simple, it just runs through a decision tree and picks appropriate actions. I was previously using prolog for the decision engine but due to the other developers using c++ and some issues with integrating the prolog code I'm now trying to port it to c++.
Currently I have a bunch of facts and rules in prolog (100+). Many express things in the form, if game_state then do action xyz. Most of the rules are fairly simple with a few being rather complex. I looked at a finite state machine approach, but that didn't seem to scale to the larger situations so well.
My first attempt at coding this up in c++ was a huge nightmare of if then else case statements. I had this sort of code popping up everywhere:
if( this->current_game_state->some_condition == true ){
if( this->current_game_state->some_other_condition == false ){
//some code
}else{
return do_default_action();
}
}else if( this->current_game->another_condition ){
//more code
}
The complexity became quickly unmanageable.
If there a good way to code this sort of problem in c++? Are there any good design patterns to deal with this type of situation? There is no requirement that the logic has to be contained within the source, it just needs to be accessible from c++. The only real requirement is that it is reasonably fast.
I also looked at rules engines and if fast enough they could be appropriate. Do you know if there is a open source c++ rules engine that would be appropriate?
Code is Data, and Data is Code. You've got working code - you just need to expose it to C++ in a way it can compile, then you can implement a minimal interpreter to evaluate it.
One possibility is to take your Prolog rules and translate them in the most direct way possible to a data structure. Maybe you could design a simple table like:
struct {
State coming_from;
Event event;
void (*func)(some, args);
State going_to;
} rules[] = {
{ WANDERING_AROUND, HEAR_SOUND, look_around, ENEMY_SEEN },
{ ENEMY_SEEN, GUN_LOADED, fire_gun, SNEEK_AWAY },
{ next, rule, goes, here },
etc...
}
Similarly, function calls can populate data structures in such a way that it looks similar to your original Prolog:
void init_rules () {
rule("Parent", "Bill", "John");
rule("Parent", "Paul", "Bill");
// 99 more rules go here...
}
Then you implement a simple interpreter to traverse that data structure and find the answers you need. With less than 1000 rules, a brute force approach at searching is likely to be fast enough, but you can always get clever later and try to do things the way a real Prolog environment would when the time comes.
You can use polymorphism. Calling a virtual function is effectively a big-ass switch/case that's done and optimized for you by the compiler.
class GameState {
virtual void do_something() { std::cout << "GameState!"; }
// some functions
virtual ~GameState() {}
};
class SomeOtherState : public GameState {
// some other functions
virtual void do_something() { std::cout << "SomeOtherState!"; }
};
class MyFinalState : public GameState {
virtual void do_something() { std::cout << "MyOtherState!"; }
};
class StateMachine {
std::auto_ptr<GameState> curr_state;
public:
StateMachine()
: curr_state(NULL) {}
void DoSomething() { curr_state->DoSomething(); }
void SetState(GameState* ptr) { curr_state = ptr; }
template<typename T> void SetState() { curr_state = new T; }
};
int main() {
StateMachine sm;
sm.SetState(new SomeOtherState());
sm.SetState<SomeOtherState>();
sm.DoSomething(); // prints "SomeOtherState!"
sm.SetState<MyFinalState>();
sm.DoSomething(); // prints "MyFinalState!"
}
In the above example, I didn't need to switch about any of the states, or even know that different states exist or what they do (in the StateMachine class, anyways), the selection logic was done by the compiler.
If you want to convert your prolog code to c++ code,
have a look at the Castor library (C++) which enable Logic Programming in C++:
http://www.mpprogramming.com/Cpp/Default.aspx
I haven't tried it out myself, so I don't know anything about it's performance.
If you want to use a state-machine, have a look at Boost.Meta State Machine
I don't really get why a finite state machine is not sufficiant for your game. It is a common way to do what you want to. You could make it data driven to stay you code clean from concrete actions. The finite state m. is also described in "AI for Game Dev" O'Reilly (David M. Bourg & Glenn Seemann)
You maybe want to split you rules in several smaller rule sets to keep the machine small and understandable.
How about use mercury? its basically built to interface with C code.
Trying to match Prolog's expressive power with state machines is like trying to outrun a car with a bicycle.
Castor is probably the way to go. It is very lightweight and allows smooth interop between Logic programming and rest of C++. Take a look at the tutorial videos on http://www.mpprogramming.com/cpp
Say i have these classes
ViewA and ViewB
In objective C using the delegate pattern I could do
#protocol ViewBDelegate{
- (void) doSomething();
}
then in ViewB interface:
id<ViewBDelegate> delegate;
then in ViewA implementation i set the delegate:
viewB.delegate = self;
and now I can call in doSomething from viewB onto any that unknown type delegate.
[delegate doSomething];
"C++ How to Program" has been the worse read an can't find simple examples that demonstrates basic design patterns.
What i'm looking for in C++ is:
events ActionScript and java
or delegates or NSNotifications in Objective C
anything that allows class A, Class B and Class C to know that ClassX
didSomething()!!!
thanks
If I were you, I wouldn't use function pointers to accomplish this task. Leave this option to the gurus ;)
In Boost, there is a beautiful library called signals. It makes your life easier! This is an example of usage:
#include <iostream>
#include <boost/bind.hpp>
#include <boost/signal.hpp>
using namespace std;
using namespace boost;
struct A
{ void A_action() { cout << "A::A_action();" << endl; } };
struct B
{ void B_action() { cout << "B::B_action();" << endl; } };
struct C
{ void C_action() { cout << "C::C_action();" << endl; } };
struct X
{
// Put all the functions you want to notify!
signal<void()> list_of_actions;
void do_something()
{
std::cout << "Hello I am X!" << endl;
list_of_actions(); // send notifications to all functions in the list!
}
};
int main()
{
X x;
A a;
B b;
C c;
x.list_of_actions.connect(bind(&A::A_action, a));
x.list_of_actions.connect(bind(&B::B_action, b));
x.list_of_actions.connect(bind(&C::C_action, c));
x.do_something();
}
This will print:
Hello I am X!
A::A_action();
B::B_action();
C::C_action();
Here is how it works.
First, you declare the place that holds the delegates:
signal<void()> list_of_actions;
Then, you "connect" it to what ever group of functions/functors/callable things you want to call.
x.list_of_actions.connect(bind(&A::A_action, a));
x.list_of_actions.connect(bind(&B::B_action, b));
x.list_of_actions.connect(bind(&C::C_action, c));
Note, that I have used bind. So, that the type of functions in the list_of_actions is the same, but we can connect it to different type of classes. So:
bind(&A::A_action, a)
This thing, produces a callable thing, of type void () as we declared the type of list_of actions earlier. Of course, you specify the instance you want to apply this member function on in the second parameter..
If you are doing multi-threaded stuff, then use its sister signals2.
Hope that helps.
anything that allows class A, Class B
and Class C to know that ClassX
didSomething()!!!
Probably you are looking for signals & slots, which has multiple implementations:
Boost
Qt
I'm sure there are more, but these are the most significant of which I'm aware.
There are no delegates/events/etc.
You can simulate interfaces using pure virtual function, see here for a similar question.
And there are the function pointers...
So basically the answer to you question is no, there are none of that in C++ (don't know about the latest standard), but there are substitutes and workarounds..
Personally I like The Impossibly Fast C++ Delegates by Sergey Ryazanov. Very neat and easy to use implementation, claimed to be faster than Boost::function.
You can find events implemented there, too. I don't use them, however. I implemented my own event handling using .NET style (sender, args).
Neither the C++ language, nor its associated Standard Library, either have delegates or events. There are of course many libraries that implement such things, or you can implement them yourself.
All i know there is a type of method called call-back method(In fact, function pointer).
Delegation? It's just a kind of wrapped call-back method, and, looks advanced
"C++ How to Program" has been the worse read an can't find simple examples that demonstrates basic design patterns
I think that the original Design Patterns book includes examples of how to implement each pattern using C++.