Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integrate c/c++ with Java native code as shared library (compiled by gcj)

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?

like image 278
qinsoon Avatar asked Nov 14 '22 10:11

qinsoon


1 Answers

you can use the jni or cni options in gcj to acomplish you goal, and your code is neither cni, nor jni code..

anyways against standard java VM, gcj promoted cni... yet must add, jni means you can take your code to various VM's

example for jni :

http://gcc.gnu.org/java/jni-comp.txt

cni is explained here : https://idlebox.net/2011/apidocs/gcc-4.6.0.zip/gcj-4.6.0/gcj_13.html

hope it helps ?

like image 194
P M Avatar answered Nov 16 '22 02:11

P M