简体   繁体   中英

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 ac/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 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM