0

I know there are plenty of tutorials about integrating C++ into Java, but whats about the other way around, a Bridge from Java to C++?

The reason i'm asking this is Android.

Every C++ developer who wanted to write applications for the android noticed at some point that there is no serious (mature) C++ api for android (infact, android is lacking an implementation of the STL).

The only API that is mature enough to write android applications in, is Java. So instead of writing an api from scratch, wouldn't it be possible to use the Java Classes from C++?

I know that this sounds merely like an unrealistic dream, but that way most C++ developers weren't forced to learn a new Language.

2
  • I guess you mean 'calling Java routines from a C++ main program' as opposed to 'calling C++ from a Java main program' ? Commented Sep 18, 2010 at 7:58
  • 3
    Learning a new language is always fun. Commented Sep 18, 2010 at 7:58

2 Answers 2

2

Essentially, Java to C++ is the same as C++ to Java, with the exception that you need to start the VM manually:

#include <jni.h>

JNIEnv* create_vm() {
    JavaVM * jvm;
    JNIEnv * environment;

    JavaVMInitArgs args;
    JavaVMOption options[1];

    args.version = JNI_VERSION_1_4;
    args.nOptions = 1;

    options[0].optionString = "-Djava.class.path=/path/to/project's/root/";
    args.options = options;
    args.ignoreUnrecognized = JNI_FALSE;

    JNI_CreateJavaVM(& jvm, (void **) & environment, & args);

    return environment;
}

The rest is the /normal/ JNI programming.


Mind that this is for real Java. Dalvik might do things differently, or completely disable them.

Sign up to request clarification or add additional context in comments.

2 Comments

I also think that dalvik does things a little different. If I fail completely to get a usable result from your provided code on the Android, I'll really have to learn Java ;-)
:) BTW, I can't really consider C++ syntax + Java stdlib not to be a "new language" - it is easier to learn Java's syntax coming from the C++ world than its classes.
1

Java API is the API for Android. NDK was never intended to replace it. You have an option to write performance critical parts of your app in C++ but that's it. I don't know why would you even want to write Activities in C++? So better not to waste your time, if you already know C++ switching to Java will be a piece of cake.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.