是否有一种独立于平台的方法来查找JVM库(Linux上的libjvm.so和Windows上的jvm.dll)的位置?
我已经尝试使用libltdl API,这确实适用于某些(可能很多)平台,但它不适用于Ubuntu。
答案 0 :(得分:1)
#include <stdio.h>
#include <stdlib.h>
#include <ftw.h>
#include <string.h>
static char* jvm_lib_fpath;
static int check_file(const char *fpath, const struct stat *sb, int typeflag) {
static const char LINUX_LIB[] = "libjvm.so";
static const char WINDOWS_LIB[] = "jvm.dll";
const char *libs[] = {LINUX_LIB, WINDOWS_LIB};
int i;
for (i = 0; i < 2; i++) {
const char* lib = libs[i];
const size_t m = strlen(lib);
const size_t n = strlen(fpath) - m;
const char* test = &fpath[n];
if (strcmp(test, lib) == 0) {
const size_t fpath_len = strlen(fpath) + 1;
jvm_lib_fpath = (char*) malloc(fpath_len * sizeof(char));
if (jvm_lib_fpath == NULL) return -1;
strcpy(jvm_lib_fpath, fpath);
return 1;
}
}
return 0;
}
static int set_jvm_lib_fpath() {
char* java_home = getenv("JAVA_HOME");
int result = ftw(java_home, check_file, 128);
return result;
}
int main() {
int result = set_jvm_lib_fpath();
if (result == 1) {
printf("jvm_lib_fpath: '%s'\n", jvm_lib_fpath);
} else {
printf("Could not find JVM library file.\n");
}
if (jvm_lib_fpath) {
free(jvm_lib_fpath);
}
return 0;
}