集成 c/c++使用Java本机代码作为共享库(由gcj编译)
gcj可以将Java代码编译为本机代码。我感兴趣的是,如果Java被编译成共享库,我们如何在C/C++程序中使用该库中的方法。
我没有成功。以下是我的尝试:
Java 代码(将被编译成共享库):
// JavaLib.java
public class JavaLib {
public static void hello() {
System.out.println("Hello, in Java Lib");
}
}
编译:
$gcj -C JavaLib.java
$gcj -fPIC -c JavaLib.class
$gcj -shared -o libJavaLib.so JavaLib.o -lstdc++
生成标头:
$gcjh -cp=. JavaLib
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);
}
编译 c++ 库用户:
$gcc -rdynamic -o CPPUser CPPUser.cpp -ldl
但在执行“CPPUser”时出现此错误:
./libJavaLib.so: undefined symbol: JavaLib::hello
Segmentation fault
有人有想法吗?是否可以在ac/c++程序中调用gcj编译的Java本机代码中的方法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可以使用gcj中的jni或cni选项来完成你的目标,并且你的代码既不是cni,也不是jni代码..
无论如何反对标准java VM,gcj提升了cni...但必须添加,jni意味着你可以使用你的代码 jni 的各种 VM
示例:
http://gcc.gnu.org/java/jni-comp.txt
cni 在这里解释:https://idlebox.net/2011/apidocs/gcc-4.6.0.zip/gcj-4.6.0/gcj_13.html
希望有帮助吗?
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 ?