Skip to content

Instantly share code, notes, and snippets.

@takanuva
Created March 1, 2014 05:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save takanuva/9285762 to your computer and use it in GitHub Desktop.
Save takanuva/9285762 to your computer and use it in GitHub Desktop.
Integrating Java and C++ with GCC/CNI :)
#!/bin/bash
# Compile Main for Java bytecode
gcj -C Main.java
# Compile Main for native
gcj -findirect-dispatch -fno-indirect-classes -fpic -c Main.class -o java.o
# Generate header file
gcjh -cp . Main
# Compile C++ file
g++ -fpic -c main.cpp -o main.o
# Link all together
gcc main.o java.o -lstdc++ -lgcj -o prog
// Main headers
#include <cstdlib>
#include <cstdio>
#include <iostream>
// Include the GNU Java runtime
#include <gcj/cni.h>
// Include the Java interface (generated with gcjh!)
#include "Main.h"
// Implement the Java method!
jint Main::sum(jint x, jint y) {
using namespace std;
cout << "Summing in C++ ;)" << endl;
return x + y;
}
//
int main() {
using namespace std;
using namespace java::lang;
JvCreateJavaVM(NULL);
JvAttachCurrentThread(NULL, NULL);
//JvInitClass(&Main::class$);
Main *m = new Main;
JvDetachCurrentThread();
return EXIT_SUCCESS;
};
public class Main {
public Main() {
System.out.println("In Java, gonna make a summation... =P");
int r = sum(5, 10);
System.out.printf("Back in Java, Sum of 5 and 10 is %d%n", r);
};
// Mark this method as native, we will implement it in C++ :)
public native int sum(int x, int y);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment