Rewrite C++ code for use wrapper class pointer instead raw pointers - c++

In a started project, I would to start using my own wrapper class pointer instead of raw pointers.
My idea was rewrite the existent code for translate declarations like "Object *a" to "MyPointerObject a", but this rewrite does not seems trivial.
What is the simplest way to perform this?
I've looked clang, elsa, gccxml and doxygen, but none of these tools seems to be either simple enough or powerful enough for my task.

Related

c++ wrapper class efficiency

I am coding some performance-sensitive tool in C++. int, long and pointers to them are used extensively for widely different purposes. I would like to provide some separation so that the code is easier to understand. I am not really concerned about bug prevention (e.g. I am making everything global), so separation of concerns in this case is more of a, say, aesthetical issue.
I would like to make subclasses of built-in types. Of course, just changing the name is easy with a typedef. However, I would also like to be able to add new methods. Say, I want to make a "subclass", or something that looks like it, cell of int*. What comes to my head is to use a wrapper for int*, then subclass it.
1) How can I reasonably define a wrapper for int* without needing to redefine almost every operator that can be applied to int*? Or else, is there any library that already defines one? I am trying to stick to the standard library, but any MIT license-compatible library would do.
2) Is there an overhead of using such a wrapper (or the subclass, for that matter) over directly using an int*? I don't plan to use polymorphism, so no virtual functions involved. It's really a matter of readability.

Modifying SWIG Interface file to Support C void* and structure return types

I'm using SWIG to generate my JNI layer for a large set of C APIs and I was wondering what is the best practices for the below situations. The below not only pertain to SWIG but JNI in general.
When C functions return pointers to Structures, should the SWIG interface file (JNI logic) be heavily used or should C wrapper functions be created to return the data in pieces (i.e. a char array that contains the various data elements)?
When C Functions return void* should the C APIs be modified to return the actual data type, whether it be primitive or structure types?
I'm unsure if I want to add a mass amount of logic and create a middle layer (SWIG interface file/JNI logic). Thoughts?
My approach to this in the past has been to write as little code as possible to make it work. When I have to write code to make it work I write it in this order of preference:
Write as C or C++ in the original library - everyone can use this code, you don't have to write anything Java or SWIG specific (e.g. add more overloads in C++, add more versions of functions in C, use return types that SWIG knows about in them)
Write more of the target language - supply "glue" to bring some bits of the library together. In this case that would be Java.
It doesn't really matter if this is "pure" Java, outside of SWIG altogether, or as part of the SWIG interface file from my perspective. Users of the Java interface shouldn't be able to distinguish the two. You can use SWIG to help avoid repetition in a number of cases though.
Write some JNI through SWIG typemaps. This is ugly, error prone if you're not familiar with writing it, harder to maintain (arguably) and only useful to SWIG+Java. Using SWIG typemaps does at least mean you only write it once for every type you wrap.
The times I'd favour this over 2. is one or more of:
When it comes up a lot (saves repetitious coding)
I don't know the target language at all, in which case using the language's C API probably is easier than writing something in that language
The users will expect this
Or it just isn't possible to use the previous styles.
Basically these guidelines I suggested are trying to deliver functionality to as many users of the library as possible whilst minimising the amount of extra, target language specific code you have to write and reducing the complexity of it when you do have to write it.
For a specific case of sockaddr_in*:
Approach 1
The first thing I'd try and do is avoid wrapping anything more than a pointer to it. This is what swig does by default with the SWIGTYPE_p_sockaddr_in thing. You can use this "unknown" type in Java quite happily if all you do is pass it from one thing to another, store in containers/as a member etc., e.g.
public static void main(String[] argv) {
Module.takes_a_sockaddr(Module.returns_a_sockaddr());
}
If that doesn't do the job you could do something like write another function, in C:
const char * sockaddr2host(struct sockaddr_in *in); // Some code to get the host as a string
unsigned short sockaddr2port(struct sockaddr_in *in); // Some code to get the port
This isn't great in this case though - you've got some complexity to handle there with address families that I'd guess you'd rather avoid (that's why you're using sockaddr_in in the first place), but it's not Java specific, it's not obscure syntax and it all happens automatically for you besides that.
Approach 2
If that still isn't good enough then I'd start to think about writing a little bit of Java - you could expose a nicer interface by hiding the SWIGTYPE_p_sockaddr_in type as a private member of your own Java type, and wrapping the call to the function that returns it in some Java that constructs your type for you, e.g.
public class MyExtension {
private MyExtension() { }
private SWIGTYPE_p_sockaddr_in detail;
public static MyExtension native_call() {
MyExtension e = new MyExtension();
e.detail = Module.real_native_call();
return e;
}
public void some_call_that_takes_a_sockaddr() {
Module.real_call(detail);
}
}
No extra SWIG to write, no JNI to write. You could do this through SWIG using %pragma(modulecode) to make it all overloads on the actual Module SWIG generates - this feels more natural to the Java users probably (it doesn't look like a special case) and isn't really any more complex. The hardwork is being done by SWIG still, this just provides some polish that avoids repetitious coding on the Java side.
Approach 3
This would basically be the second part of my previous answer. It's nice because it looks and feels native to the Java users and the C library doesn't have to be modified either. In essence the typemap provides a clean-ish syntax for encapsulating the JNI calls for converting from what Java users expect to what C works with and neither side knows about the other side's outlook.
The downside though is that it is harder to maintain and really hard to debug. My experience has been that SWIG has a steep learning curve for things like this, but once you reach a point where it doesn't take too much effort to write typemaps like that the power they give you through re-use and encapsulation of the C type->Java type mapping is very useful and powerful.
If you're part of a team, but the only person who really understands the SWIG interface then that puts a big "what if you get hit by a bus?" factor on the project as a whole. (Probably quite good for making you unfirable though!)

Trouble with adding C++ objects to Objective C collections (NSSet)

I'm busy implementing ZXing with a QRCodeReader into my project.
QRCodeReader is mainly C++ and my project objective-C.
I have managed to implement it properly so I can use the QRCodeReader objects into my objective-C implementation (.mm file).
But now I need to pass this C++ object to the zxWidController.reader property.
This means I will have to set the C++ object into an NSSet Object.
QRCodeReader* qrcodeReader = new QRCodeReader();
NSSet *readers = [[NSSet alloc ] init];
[readers setByAddingObject:(id)qrcodeReader];
widController.readers = readers;
[readers release];
The code above does the trick. I casted the C++ object to (id) and now it compiles properly. But is this the proper way to do it?
Is this manner of programming the proper way to do this?
Are there any other / better ways to achieve my goal?
A C++ type is not an Objective C type. You cannot send it messages, in particular retain and release, which NSSet does. There's an Objective C type of the same name that you want to use. (I'll update my other answer).
The code above does the trick. I casted the C++ object to (id) and now
it compiles properly. But is this the proper way to do it?
No. You can't just make an arbitrary pointer into a valid Objective-C object pointer by casting it to id.
Is this manner of programming the proper way to do this?
Again, no.
Are there any other / better ways to achieve my goal?
You can try any of the following:
Redefine your zxWidController class to take a pointer to a C++ object instead of an Obj-C object.
Wrap qrcodeReader in a NSValue.
Take a look at NSPointerArray as a replacement for NSSet. Definitely read the docs before you try to use it -- you have to configure it's memory management policies to do the right thing for the type of pointer you're storing.
Minor nitpick: Forgetting for a moment about the fact that qrcodeReader points to a C++ object, it seems silly to create an empty set just so that you can add an object to it. If you were going to use an Obj-C set, then either create it using +setWithObject: or use NSMutableSet instead.

How do I get a list of all declared classes inheriting from a particular class in C++

I know that isn't exactly possible in C++, but maybe a toolchain that can generate code which has a function, which when called gives me a list of all those classes. For example, across multiple files I have stuff like:
class MyClass : public ParticularClass {
....
}
class MyClass2 : public ParticularClass {
....
}
Then, during runtime, I just want a pointer to single instances of the class. Let's say my generated code looks something like this:
void __populate_classes() {
superList.append(new MyClass());
superList.append(new MyClass2());
}
Also, superList would be of type List<ParticularClass*>. Plus, I'll be using Qt and ParticularClass will be QObject derived, so I can fetch the name of the class anyways. I need to basically introspect the class, so my internal code doesn't really bother much about the newly defined type.
So, is there a way to generate this code with some toolchain? If it is possible with qmake alone, that'd be like icing on the freaking cake :)
Thanks a lot for your time.
Doxygen does a nice job at doing this -- offline. Various IDEs do a nice job at this -- offline. The compiler does not do this. Such knowledge is not needed or used by the compiler.
Here at work I use a tool called Understand 4 C++. It is a tool that helps you analyze your code. It will do this quite easily.
But my favorite part is it comes with a C and Perl API which allows you to take advantage of the abstract syntax tree that 'understand' encapsulates and write your own static analysis tools. I have written tons of tools using this API.
Anyways, it's written by SciTools. http://scitools.com and I don't work for them. I just wholeheartedly like their product. In fact I wrote a C# API that wraps their C API and posted it on CodePlex a few years ago. Sure beats using C or Perl to write static analysis tools.
I don't think what you're trying to do is a good idea. Those who will maintain code after you will have hard times to understand it.
Maybe instead of it you'll try see how you can do it in plan C++. One possible solution which comes to mind i to implement factory design pattern. Than you can iterate over all data types in factory and add then to superList.
Any way, using ack (simple grep replacement) can do the job if you always declare the inheritence in one line:
ack ": *public ParticularClass" *.h

A more natural boost::bind alternative?

Don't get me wrong: Boost's bind() is great.
But I do hate to write&read code with it, and I've given up hope my coworkers will ever grok/use it.
I end up with code like this:
btn.clicked.connect(bind(&BetBar::placeBet, this, bet_id));
animator.eachFrame.connect(bind(&Widget::move, buttons[bet_id]));
Which, while logical, is very far from what I'd call nice code.
To demonstrate... in C++1x we'll have this:
btn.clicked.connect([&](int bet_id){ placeBet(bet_id); })
animator.eachFrame.connect([&](Point newPos) { buttons[bet_id].move(newPos) })
And a good DSL could look kinda like this:
on(btn.clicked) placeBet(bet_id);
on(animator.eachFrame) buttons[bet_id].move(eachFrame::newPos);
How do you cope with binding in C++? Do you just live with what boost gives you?
It seems you want the following:
Implicit binding to this
An alternative for the parentheses associated with the function call which stores the binding.
Automatic identification which parameters in your lambda-expression are bound.
The first is very hard in C++ today, as this is implicit in very few contexts, and you certainly cannot pass it to functions implicitly. I.e. you can't achieve this with a library function, but you could with a macro. Still, it would be ugly.
The second part is far easier:
button.clicked.handler = bind(BetBar::placeBet, this, bet_id);
This just requires handler.operator=(boost::function<void(*)()> const&)
The third is hard again, because you have just designed another case of two-phase name lookup. That was hard enough with templates. boost's _1 trick works by making it explicit which arguments should be bound later. However, _1 as name isn't magic. It's basically a free function returning boost::arg<1>. So, with a suitable definition of animator.eachFrame.newPos the following could be made equivalent:
animator.eachFrame.handler = bind(&Widget::move, buttons[bet_id], _1)
animator.eachFrame.handler = bind(&Widget::move, buttons[bet_id], animator.eachFrame.newPos)
I doubt you can get any better then this on pre-0x C++. Boost.Lambda or Phoenix provide their own binding mechanisms, but for such cases it won't get any more readable, really.
If you could think of how to program such a DSL within the current C++ using boost::proto (are there any other alternatives?), well, then you may get better help by the only other proto-guys on the boost mailing list itself, as this would be over my head.
For the co-workers: When they are doing programming C++ professionally (read: they get paid for it), they either grok it, or they should do another job. If they can't read such simple constructs, they will probably produce a bigger maintenance burden then they can ever make up with helping on implementing new features.
In such a case, providing a nice binding to Lua (or whatever scripting language you prefer), and make them do the business logic in that language. This is actually a not too bad solution, anyway.
As a side note, actually a good DSL could look kinda like this:
btn.clicked { |bet_id| placeBet bet_id }
animator.eachFrame { |newPos| buttons[bet_id].move newPos }
To answer your question: For the simple example you provided a plain bind works just fine.