문제

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?

도움이 되었습니까?

해결책

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 ?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top