我需要使用Java Native Interface(JNI)在我的C ++应用程序和我的Java应用程序之间进行通信。
我开始从JVM.Lib
生成JVM.DLL
。为此,我使用了impdef
和implib
。我在项目Builder C ++中添加了我的设置(包括路径和库路径)。
但是,我的程序会生成
错误链接JNI_CreateJavaVM。
如何修复此错误?如何在我的应用程序Builder C ++中使用JNI?
答案 0 :(得分:0)
我成功修复了这个错误..我使用Coff2Omf命令生成我的lib
coff2omf jvm.lib jvm2.lib
之后,我添加了jvm2.lib并在我的设置中包含路径..
这是调用方法java的示例C ++代码:
#include <windows.h>
#include <stdio.h>
#include <jni.h>
#include <string.h>
#define PATH_SEPARATOR ';' /* define it to be ':' on Solaris */
#define USER_CLASSPATH "." /* where Prog.class is */
typedef /*_JNI_IMPORT_OR_EXPORT_*/ jint (JNICALL *JNI_CreateJavaVM_func)(JavaVM **pvm, void **penv, void *args);
JNI_CreateJavaVM_func JNI_CreateJavaVM_ptr;
JNIEnv* create_vm(JavaVM ** jvm)
{
JNIEnv *env;
JavaVMInitArgs vm_args;
JavaVMOption options;
memset(&vm_args, 0, sizeof(vm_args));
options.optionString = "-Djava.class.path=."; //Path to the java source code
vm_args.version = JNI_VERSION_1_6; //JDK version. This indicates version 1.6
vm_args.nOptions = 1;
vm_args.options = &options;
vm_args.ignoreUnrecognized = 0;
HMODULE jvm_dll = LoadLibrary("C:\\Program Files (x86)\\Java\\jdk1.7.0_65\\jre\\bin\\server\\jvm.dll");
/// You might check the GetLastError() here after the LoadLibrary()
if(jvm_dll == NULL)
{
printf("can't load dll\n");
exit(1);
}
JNI_CreateJavaVM_ptr = (JNI_CreateJavaVM_func)GetProcAddress(jvm_dll, "JNI_CreateJavaVM");
/// You might check the GetLastError() here
if(JNI_CreateJavaVM_ptr == NULL)
{
printf("can't load function\n");
exit(1);
}
int ret = JNI_CreateJavaVM_ptr(jvm, (void**)&env, &vm_args);
if(ret < 0)
{
printf("\nUnable to Launch JVM\n");
}
return env;
}
int main(int argc, char* argv[])
{
JNIEnv *env;
JavaVM * jvm;
env = create_vm(&jvm);
if (env == NULL) { return 1; }
jclass cls;
jmethodID mid;
jint square;
jboolean not;
cls = (*env).FindClass("Sample2");
if(cls !=0)
{ mid = (*env).GetStaticMethodID(cls, "intMethod", "(I)I");
if(mid !=0)
{ square = (*env).CallStaticIntMethod(cls, mid, 5);
printf("Result of intMethod: %d\n", square);
}
mid = (*env).GetStaticMethodID(cls, "booleanMethod", "(Z)Z");
if(mid !=0)
{ not = (*env).CallStaticBooleanMethod( cls, mid, 1);
printf("Result of booleanMethod: %d\n", not);
}
}
int n = jvm->DestroyJavaVM();
return 0;
}