Bitcoin Forum

Bitcoin => Wallet software => Topic started by: Mike Hearn on May 03, 2012, 08:09:43 AM

Title: Using bitcoinj in native C++/Objective-C++ apps
Post by: Mike Hearn on May 03, 2012, 08:09:43 AM
I've uploaded some preliminary work on using the lightweight-mode bitcoinj library from (Objective) C++. Although this work is still quite incomplete, it's enough to have a working native Cocoa app that uses the bitcoinj Java API to load a wallet file and put its details into a window.

The eventual goal of this is to allow people who are happier with native code development to use the bitcoinj API, and to open the possibility for a pure p2p iOS app (though the release of piuks app makes this less important now). I'd like bitcoinj to become one of the premier APIs for all bitcoin app development and this is a crucial next step.

The resulting compiled apps don't depend on the JVM and are just regular native binaries. This trick is achieved using GCJ and the CNI interface. It allows you to use the Java API as if it were a more or less regular C++ API, with the exception that it's still garbage collected so you never have to use the delete keyword.

This is what the code looks like:

Plain C++:
Objective C++:

As you can see, the code is fairly natural looking because Java is essentially a subset of C++. Java packages become C++ namespaces, you create objects with new, call methods on them using ->, you can catch java exceptions with C++ try/catch and so on. Like many C++ APIs it has a different string type, jstring, helpers are provided to convert back and forth between char*, std::string and Apples NSString. You can see the full language mapping here:

and the helper routines here:

There are rough notes here:

At this time the native branch of bitcoinj is incomplete and only suitable for advanced developers. You should be comfortable with both Java and native code development. If you want to use IDEs such as Xcode you will need to ask me for how I set it up. There is no documentation beyond the notes and the demos. The resulting apps are very large because no dead code elimination is done by default and libgcj is not statically linked. In future things will get simpler and more optimized.