gcj can compile Java code into native code. I am interested if Java is compiled into shared library, how we can use methods from the library in c/c++ programs.
I didn't succeed. The following is my attempt:
Java code (will be compiled into shared library):
// JavaLib.java
public class JavaLib {
public static void hello() {
System.out.println("Hello, in Java Lib");
}
}
Compile:
$gcj -C JavaLib.java
$gcj -fPIC -c JavaLib.class
$gcj -shared -o libJavaLib.so JavaLib.o -lstdc++
Generate header:
$gcjh -cp=. JavaLib
Library user in c++:
#include <stdio.h>
#include <dlfcn.h>
#include "JavaLib.h"
using namespace std;
int main(int argc, char **argv) {
void * handle = dlopen("./libJavaLib.so", RTLD_LAZY);
char * error;
if (!handle) {
fprintf(stderr, "%s\n", dlerror());
}
void (*hello)();
hello = (void (*)())dlsym(handle, "JavaLib::hello");
if ((error = dlerror()) != NULL) {
fprintf(stderr, "%s\n", error);
}
hello();
dlclose(handle);
}
Compile c++ library user:
$gcc -rdynamic -o CPPUser CPPUser.cpp -ldl
But I got this error when executing 'CPPUser':
./libJavaLib.so: undefined symbol: JavaLib::hello
Segmentation fault
Does anyone have an idea? Is it possible to invoke methods from Java native code compiled by gcj in a c/c++ program?