问题描述
写了两个java类,如下:publicclassMyClassA{publicStringmyString1;privateStringmyString2;publicMyClassA(){}publicMyClassA(Stringss){myString1=ss;myString2=ss;}publicStringgetMyString(intwhichString){if(whichString==1)returnmyString1;elsereturnmyString2;}publicvoidsetMyString(intwhichString,Stringss){if(whichString==1)myString1=ss;elsemyString2=ss;}}publicclassUseClassA{publicMyClassAaclass;publicUseClassA(){aclass.setMyString(1,"IloveJava");aclass.setMyString(2,"IdonotloveJava");}publicUseClassA(Stringss){aclass.setMyString(1,ss);aclass.setMyString(2,ss);}publicvoidsetMyString(intwhichString,Stringss){aclass.setMyString(whichString,ss);}publicStringgetMyString(intwhichString){returnaclass.getMyString(whichString);}publicStringgetSubString(Stringss){returnnewString(ss);}}现在在C++中调用类UseClassA:intmain(){//*****创建java虚拟机和环境****intcreatjavavm_res;JavaVMInitArgsvm_args;JavaVMOptionoptions[3];JavaVM*jvm;JNIEnv*env;options[0].optionString="-Djava.compiler=NONE";options[1].optionString="-Djava.class.path=.;E:\eclipse\workspace\SimpleJavaTest;";options[2].optionString="-verbose:NONE";vm_args.version=JNI_VERSION_1_4;vm_args.nOptions=3;vm_args.options=options;vm_args.ignoreUnrecognized=JNI_TRUE;HINSTANCEhInstance=::LoadLibrary("D:\ProgramFiles\Java\jdk1.6.0_02\jre\bin\client\jvm.dll");if(hInstance==NULL){returnfalse;}PFunCreateJavaVMfunCreateJavaVM=(PFunCreateJavaVM)::GetProcAddress(hInstance,"JNI_CreateJavaVM");creatjavavm_res=(*funCreateJavaVM)(&jvm,(void**)&env,&vm_args);if(creatjavavm_res<0){cout<<"Cannotcreatejavaenvironment."<<endl;return-1;}//******创建java虚拟机和环境完毕*****jstringretJString;stringretString;jmethodIDmethodID;jclasscls=env->FindClass("UseClassA");jobjectmyUClassA=env->AllocObject(cls);methodID=env->GetMethodID(cls,"setMyString","(ILjava/lang/String;)V");retString="ModifiedString";retJString=NewJString(env,retString.c_str());env->CallVoidMethod(myUClassA,methodID,1,retJString);methodID=env->GetMethodID(cls,"getMyString","(I)Ljava/lang/String;");retJString=(jstring)(env->CallObjectMethod(myUClassA,methodID,1));retString=JStringToCString(env,retJString);cout<<retString.c_str()<<endl;return0;}其中NewJString和JStringToCString分别为将c中的字符串转换为jstring和将jstring转换为c中的字符串的函数,已经经过测试,没有问题。现在的问题是retJString=(jstring)(env->CallObjectMethod(myUClassA,methodID,1))这句返回的retJString总是NULL,请高手帮忙解决一下,感激不尽.....
解决方案
解决方案二:
友情帮顶吧
解决方案三:
头像左边这个表示等级的裤衩真是升得太慢了