本示例使用的jdk为 adopt-openj9-11.0.10
核心API是调用windows的GetProcAddress
hjvmlib = loadJVMLibrary();
createJavaVM = (CreateJavaVM_t) GetProcAddress(hjvmlib, "JNI_CreateJavaVM");
status = (*createJavaVM)(&jvm, (void **) &env, &vm_args);
这个方法能调起dll的库函数
dll导入
static HINSTANCE loadJVMLibrary(void)
{
HINSTANCE h1, h2;
char msvcdll[MAX_PATH] = /** JDK目录 **/;
char javadll[MAX_PATH] = /** JDK目录 **/";
//GetPublicJREHome(msvcdll, MAX_PATH);
strcpy(javadll, msvcdll);
strncat(msvcdll, "\\bin\\msvcp140.dll", MAX_PATH - strlen(msvcdll));
msvcdll[MAX_PATH - 1] = '\0';
strncat(javadll, "\\bin\\j9vm\\jvm.dll", MAX_PATH - strlen(javadll));
javadll[MAX_PATH - 1] = '\0';
h1 = LoadLibrary(msvcdll);
if (h1 == NULL)
{
fprintf(stderr, "Can't load library msvcp140.dll\n");
exit(1);
}
h2 = LoadLibrary(javadll);
if (h2 == NULL)
{
fprintf(stderr, "Can't load library jvm.dll\n");
exit(1);
}
return h2;
}
配置jvm参数
JavaVMOption options[2];
JavaVMInitArgs vm_args;
JavaVM *jvm;
JNIEnv *env;
long status;
jclass class_Welcome;
jclass class_String;
jobjectArray args;
jmethodID id_main;
#ifdef _WINDOWS
HINSTANCE hjvmlib;
CreateJavaVM_t createJavaVM;
#endif
options[0].optionString = "-Djava.class.path=.";
//options[1].optionString = "-Dfile.encoding=UTF-8";
memset(&vm_args, 0, sizeof(vm_args));
vm_args.version = JNI_VERSION_10;
vm_args.nOptions = 1;
vm_args.options = options;
测试代码
2个java
package com.ccand99;
public class Welcome {
public Welcome() {
}
public static void main(String[] args) {
var china = new China();
china.printf();
}
}
package com.ccand99;
public class China {
public void printf(){
System.out.println("中国");
}
}
c执行Weclome,注意目录=包名
if (status == JNI_ERR)
{
fprintf(stderr, "Error creating VM\n");
return 1;
}
class_Welcome = (*env)->FindClass(env, "com/ccand99/Welcome");
id_main = (*env)->GetStaticMethodID(env, class_Welcome, "main", "([Ljava/lang/String;)V");
class_String = (*env)->FindClass(env, "java/lang/String");
args = (*env)->NewObjectArray(env, 0, class_String, NULL);
(*env)->CallStaticVoidMethod(env, class_Welcome, id_main, args);
(*jvm)->DestroyJavaVM(jvm);
return 0;