Options for refactoring bits of code away from native C++? - c++

So, one commonly heard comment when talking about performance is that you write your code with whatever language gets the job done fastest. If performance in specific areas is a problem, then rewrite those bits in C/C++.
But, what if you're starting with a native C++ app? What options do you have if you want to write the easy bits, or refactor the old bits, in a language like Python, Ruby, C#, or whatever? Keep in mind that transferring data between the native and other sides is a must. Being able to simply call a function written in an "easier" language, while passing C++ classes as data, would be beautiful.
We've got a crusty Win32 app that would benefit greatly if we could crank out new code, or refactor old code, in C# or something. Very little of it requires the complexity of C++, and dealing with the little fiddly bits is dragging down the programming process.

As Aaron Fischer suggests, try recompiling your C++ application with the /clr option turned on and then start leveraging the .Net platform.
CLI/C++ is pretty easy to pick up if you know C# and C++ already and it provides the bridge between the .Net world and native C++.
If your current C++ code can't compile cleanly with /clr turned on then I'd suggest trying to build your application as a static lib (without /clr enabled) and then have your main() be in a CLI/C++ project that calls your legacy app entry point. That way you can at least start leveraging .Net for new functionality.
For examples of "legacy" C/C++ apps that have been "ported" to .Net CLI/C++ check out the .Net ports of Quake 2 and Quake 3: Arena.

Well, it really depends on the language. Python interfacing, for instance, is most easily done with Boost Python, and many other languages will require you to interface them as you would with C, using their C library and declaring your callbacks to be extern "C" (unfortunate that you can't use the C++ class definitions in other languages usually).
But I would also ask what you intend to use it for as C++ is a complex language, but once you get familiar with it, it is very powerful and not very much harder to code than other languages. The only really good exception I could think of is if you plan on using a powerful library that exists only in one language and there isn't a decent C++ alternative (graphics libraries are probably the best example of this because you have to be very familiar with them to use them effectively).
It's also worth pointing out that if you interface C++ code to another language, you lose out on the inter-platform compatibility granted by that language.

If you want to work between C++ and Python, than Boost Python is what you're looking for. You can write C Python bindings by hand for Cython, but that limits in many ways how you're going to write your code. This is the easiest way, as seen in some snippets from this tutorial:
A simple function that performs a hello world:
char const* greet()
{
return "hello, world";
}
The Boost python code needed to expose it to python:
#include <boost/python.hpp>
BOOST_PYTHON_MODULE(hello_ext)
{
using namespace boost::python;
def("greet", greet);
}
How to use this code from python:
>>> import hello_ext
>>> print hello.greet()
hello, world
Going in the opposite direction is bit tougher, since python doesn't compile to native code. You have to embed the python interpreter into your C++ application, but the work necessary to do that is documented here. This is an example of calling the python interpreter and extracting the result (the python interpreter defines the object class for use in C++):
object result = eval("5 ** 2");
int five_squared = extract<int>(result);

You can change the common Language run time support in your c++ project to /clr. From this point you can use any .net functionality right in your c++ code. This includes creating winforms in your project as well. You can also add a c# library that handles ui and other functionality.

In the .NET world you always have the option of crreating a COM/ActiveX interop layer for your C#/VB.NET assembly.
You can then use the normal COM API from your C++ application to create an instance of this COM server that actually wraps your .NET assembly.
Good thing about this is that simple parameters such as int, bool, string, float etc are mapped to their COM equivalent for you. However to my knowledge it is not possible to easily pass full .NET objects (instances of classes you create).
Also be aware that COM interop calls are relatively slow. You should not be calling a COM interop method continually from your C++ code in a tight loop.
COM/ActiveX have traditionally relied on the Windows Registry, not ideal as it is a big dependency. However it is also possible to to use Registration-Free COM interop to avoid this dependency.
This article covers the steps required to register a .NET assembly for COM interop.

Related

ReactNative expose C++ native module

We have a lot of business logic written in cross-platform C++. We want to write cross-platform UI for our application and use this business logic to create whole cross-platfrom application.
Is it possible to expose native module purely written in C++ to react-native?
We don't want to create wrappers around C++ code in native language (Java or Objective-C). Such wrappers will add more complexity it will make debugging and investigation much harder.
I am also looking for a way to do this directly in C++ without writing JNI for Android and Obj-C for iOS. I have found the CxxNativeModule class in the react native source. See the sample implementation SampleCxxModule.
The last thing to figure out is how to register that module in C++. In the JNI for React Native Android, implementation of NativeModule says
NativeModules whose implementation is written in C++ must not provide
any Java code (so they can be reused on other platforms), and instead
should register themselves using CxxModuleWrapper.
Then implementation of CxxModuleWrapper says
This does nothing interesting, except avoid breaking existing code.
So, this may help you get started. The last thing to figure out is how to register a CxxNativeModule so that it can be used in JS.
It seems as though you would need to find the code which is os dependent and write different versions of this code for different operating systems.
Here is a link which suggests how this might be done:
How do I check OS with a preprocessor directive?

Can I use pure native C++ to write apps for windows 8 metro?

With native c++, I mean, not managed c++, not cli, not any special things from microsoft, I can:
1) get high performance
2) use existing c++ code library and engine
3) write cross platform code (for example, for ios and android)
it needn't be fully native c++, I can use managed code to do the ui things, like object-c in ios and java in android, but beside interface, can I use native c++ code?
I suggest you have a look at the presentation here: Using the Windows Runtime from C++ and especially at the comments from Herb Sutter. I quote:
Please answer this question: If I decide to write C++ GUI application
in Metro style am I forced to use all these proprietary ref, sealed,
^, Platform::String^ extensions for GUI components or not?
#Tomas: No, you are not forced to use them. We are providing two
supported ways:
1) These language extensions (C++/CX).
2) A C++ template library (WRL), see
Windows Kits\8.0\Include\winrt\wrl as Yannick mentioned. WRL is a C++
library-based solution sort of along the lines of ATL, which offers
what I think you're looking for -- template wrapper/convenience
classes and explicit smart pointers and such.
Yes you absolutely can, real native C++ is fully supported.
You do however mostly have to use the new WinRT libraries to do an user interface or system calls and although they are native code and fully callable from C++ directly the interface to them makes it very painful indeed to do so, as everything is a reference counted COM object and in addition it's not so easy to create instances of them as just calling "new" so you have to write a lot of ugly code to do so.
As the earlier answer said, microsoft provide two ways to help with this. One is via language extensions to c++ and the other is a c++ template library. Personally I consider both to be rather ugly for doing something as simple as calling an API but that's just me :)
But to answer your question, it's completely possible to write your application in real native c++. You won't need to use managed code at all for anything. But you'll probably want to use either the language extensions or the template library to make calling the API more easy.
Personally I'm hoping someone writes a wrapper for WinRT that exposes the most necessary functionality as a more usable c++ native library and then everyone can just use that from c++ instead...

Advice on whether to use native C++ DLL or not: PINVOKE & Marshaling?

What's the best way to do this....?
I have some Native C++ code that uses a lot of Win32 calls together with byte buffers (allocated using HeapAlloc). I'd like to extend the code and make a C# GUI...and maybe later use a basic Win32 GUI (for use where there is no .Net and limited MFC support).
(A) I could just re-write the code in C# and use multiple PINVOKEs....but even with the PINVOKES in a separate class, the code looks messy with all the marshaling. I'm also re-writing a lot of code.
(B) I could create a native C++ DLL and use PINVOKE to marshal in the native data structures. I'm assuming I can include the native C++ DLL/LIB in a project using C#?
(C) Create a mixed mode DLL (Native C++ class plus managed ref class). I'm assuming that this would make it easier to use the managed ref class in C#......but is this the case? Will the managed class handle all the marshaling? Can I use this mixed mode DLL on a platform with no .Net (i.e. still access the native C++ unmanaged component) or do I limit myself to .Net only platforms.
One thing that bothers me about each of these options is all the marshalling. Is it better to create a managed data structure (array, string etc.) and pass that to the native C++ class, or, the other way around?
Any ideas on what would be considered best practice...?
UPDATE:
I know I can re-write the native C++ code from scratch, but it means duplicating the code and prevents me from easily reusing any code updates with any Win32 application. What concerns me most is the best way to marshal the various data between the managed and unmanaged world. To me, a mixed mode DLL looks like the most flxible option, but I'd like to get a different perspective on the potential pitfalls.
Why not just use .NET directly? It seems to me like your problem arises from the fact that you are dependent on the original native library, but you don't mention that it can't simply be re-done in .NET.
As for .NET-native interop, PInvoke is messy, but it does work. I'd go with that if you can't change the original DLL into .NET.
Option C gives you the least work if the marshaling turns out to be simple and easy for the framework to handle (is everything blittable?). It also gives you a place to hook in your own marshaling. I wrote something about this ages ago marshaling between date types etc but I think today I would write a marshal_as<> overload between your managed and native types. It would be the most elegant solution and also the least code.
Update: found my old article - it was for PInvoke. http://codeguru.earthweb.com/columns/kate/article.php/c4867/

Best way to convert Delphi code to C++?

I have an application written in Delphi that compiles in Delphi 2007. I think it was originally written in Delphi 7.
Anyway, I need to convert all the core non-GUI code into C++ because I want to release a Mac version of the software.
What is the best way to do this? Any shortcuts I can take to speed up the process?
EDIT: The code compiles to native code, not .NET.
Simple answer: You simply can't port non-trivial Delphi code to C++ without a complete rewrite. C++'s object model is very different from Delphi's. It doesn't have a base class like TObject from which all other objects are derived, and it lacks support for a lot of the RTTI stuff that Delphi code often takes for granted. And there's no simple way to reimplement Delphi RTTI in C++, since a lot of it's done at the compiler level, and a lot of it's based on the fact that all Delphi classes descend from TObject.
C++ also lacks support for the concept of unit initialization and finalization sections that are so common in Delphi, and what it has instead is badly broken. (Look up the "static order initialization fiasco" for all the gory details.)
Delphi's exception handling is also much more advanced than C++'s. Part of this is the object model and part of it's compiler magic. Plus, C++ has no support for the try-finally construct.
If you want to port a Delphi project to the Mac, Free Pascal is your best solution. It's not 100% compatible with Delphi, but it's good enough for a lot of things, and you specifically mentioned that you don't need to port the Delphi GUI stuff. AFAIK the GUI area is the source of most of FPC's compatibility weaknesses, so if that's not necessary, FPC is probably pretty close to ideal for your needs, at least until CodeGear gets an OSX compiler out. (Which hasn't been officially announced, but based on various things that have been said it's not unreasonable to suppose that one will be available sometime next year.)
For converting your code from Delphi to Cpp, have a look at
http://ivan.vecerina.com/code/delphi2cpp/.
I used this to convert some of the classes and functions in SysUtils, DateUtils and StrUtils using wxWidgets functions. If you are planning to use wxWidgets for C++ have a look at http://twinforms.com/products/wxwidgets/wxvcl.php which has all the converted source.
If you want directly develop Mac OSX applications using then have a look at wxForms for Delphi - http://twinforms.com/products/wxformsdelphi/index.php
I think this would be difficult to do mechanically, so you are probably looking at a complete re-write. One thing to bear in mind is that typically Delphi uses try...finally structures for resource management, whereas C++ uses a technique known as RAII (resource acquisition is initialisation). You should read up on this and other C++ idioms before you attempt the conversion.
If your code compiles in Delphi 2007 into .NET assemblies, you may have a much easier option than trying to port from Delphi's object pascal to C++.
You could potentially compile your logic into .NET assemblies (and maybe even portions of the UI), and use Mono to run it on Mac. You could write a custom GUI around Mono, or even potentially make a single, platform independent application.
You can use also Delphi Prism. It's for .NET, but it's the last expression in Delphi language spec. It supports also Mac OSX (see the link). Also the guys from CodeGear/EMBT are in the works for a new compiler as well as for a new version of Delphi which is expected to enter in beta in April and narrow the gap between Prism and RAD studio. See their 'Beta Programs' page.
The "correct" way to do this is to rewrite it in Objective C. I find Objective C a little weird, but there are a lot of similarities with Delphi in the way objects connect and delegate.
You may be able to use Free Pascal to do it more quickly, but you should seriously consider a rewrite.
I would be in love with Embarcadero if they could release a Mac OS X version of Delphi that didn't, you know, suck like Kylix did. One can dream.
Edit: There is a great benefit to staying in Delphi, and having a separate version for the Mac in Objective C. First, it means you don't need to rewrite the version on Windows, losing the (presumably) years of investment in Delphi code. Second, Mac software operates differently than Windows, from a UI perspective. A simple port of the product is inappropriate, and hobbles the developer from using the great native features of Windows and Mac. See: older versions of MS Word for Mac, or iTunes for Windows. They look and feel wrong.

Looking for a set of rich cross-platform libraries for c++

Are their any libraries which provide functionality similar to mono but for the c++ language? I know boost exists, but I like mono much more than boost.
I'm looking to do more than what's available in the base library set, like play sound more easily (crossplatform), GUI, load images, time, etc. I guess I am looking for what people might consider an engine or a large library.
Mono is a .NET implementation. Mono is NOT a library.
There is NO Mono for C++. At least, not yet.
I think you want a multi-platform framework, such as Qt
If you're wanting to work with Managed C++ a la .Net, then you would just use Mono. They have a page describing how to go about it. The only catch is that you have to compile on Windows, as there is not yet any flavor of GCC that outputs .Net CLI for C++.
To be honest, though, if you're going to use Mono, you might as well move into C#. It's a much cleaner language, IMO.
CLI is only able to host C++ compiled code on all supported platforms as long as the compiled code only contains CIL not native code.
for more detail visit
http://www.mono-project.com/CPlusPlus
I'm not sure about your precise requirements, but in terms of large multi-purpose packages: Qt has been mentioned by a few folks. wxWidgets (formerly wxWindows) is another option. GTK is multiplatform.
As you use the word "engine" (often a game-related term), you might be interested in SDL, which has been used by numerous games, professional and amateur alike. SFML is an option. ClanLib is another long-lived library I've heard of, though I'll admit to knowing little about it.
Try the STL collections...Has nothing to do with .NET, but they are a nice collection of collections (lol) and make C++ life easier.
It sounds like what you are really looking for is a C++ framework that offers the kinds of functionality found in the .NET/Mono framework. Qt is a popular choice.
On the topic of C++ interoperability, Mono has recently made some pretty big strides with CXXI.
(From this posting): The short story is that the new CXXI technology allows C#/.NET developers to:
Easily consume existing C++ classes from C# or any other .NET
language
Instantiate C++ objects from C#
Invoke C++ methods in C++ classes from C# code
Invoke C++ inline methods from C# code (provided your library is compiled with -fkeep-inline-functions or that you provide a surrogate
library)
Subclass C++ classes from C#
Override C++ methods with C# methods
Expose instances of C++ classes or mixed C++/C# classes to both C# code and C++ as if they were native code.
CXXI is the result of two summers of work from Google's Summer of Code towards improving the interoperability of Mono with the C++ language.