Run Java using C++ and the opposite

Hi all,

i would like to ask:

(1) How can i run a Java program using C++ ?

(2) How can i do the opposite, to run a C++ program using Java ?

Are there any simple, tutorial-like, examples ?

Thanks !
closed account (o1vk4iN6)
You can't do either. You might be able to find a compiler that compiles C++ into Java byte-code, or vise versa, but odds are it won't work depending on what libraries the program relies on.

Why would you want to do either, you can do anything you want in either languages, many libraries exist for both languages why not just use those.
Last edited on
You could create a finalized program, like a .so/.dll and then plug it into the other, but it would have to have some pretty complex linking.
Maybe JNI (Java Native Interface) is what you want.
closed account (3hM2Nwbp)

(1) How can i run a Java program using C++ ?

(2) How can i do the opposite, to run a C++ program using Java ?


JNI is what you're looking for...but trust me it's a royal pain in the neck to work with until you get enough experience with it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* Java */
package org.test.Test;

public class Test
{
  public Test() { }
  private native void print();
  private void print2() { System.out.println("Test From Java"); }
  public static void main(String[] args)
  {
    System.loadLibrary("Test");
    Test test = new Test();
    test.print();
  }
}

/* C++ */
/* Make me into *.dll or *.so */

/* With GCC, use flag --Wl,kill-at */

/* MSVC Works without confusing obscure compiler flags */

#include <jni.h>
#include <iostream>

extern "C"
{
  JNIEXPORT void JNICALL Java_org_test_Test_print(JNIEnv* env, jobject thisPointer)
  {
    std::cout << "Test" << std::endl; // <-- Calling C++ from Java
    env->CallVoidMethod(thisPointer, env->GetMethodID(env->FindClass("org/test/Test"), "print2", "()V"); // <-- Calling Java from C++
  }
}


Are there any simple, tutorial-like, examples ?


I haven't seen any decent tutorials that cover everything that you need to know before working with it. Sun/Oracle has one out, but it seems outdated and it doesn't cover any of the pitfalls that you can encounter like caching environment contexts and threading in enough detail.
Last edited on
Topic archived. No new replies allowed.