问题描述
- C++ 调用Jni 返回json字符串时产生的问题,穿入参数后返回的字符串是空的
-
java代码如下:
package com.iscas.test;
import java.util.ArrayList;
import com.google.gson.Gson;
import net.sf.json.JSONSerializer;
public class Test {
public String getItemList(int id,String name,float score)
{
ItemList list = new ItemList();
Item item = new Item();
item.id = id;
item.name = name;
item.score = score;list.itemList = new ArrayList();
list.itemList.add(item);
list.itemList.add(item);
list.itemList.add(item);list.num = 3;
Gson gson = new Gson();
String json = gson.toJson(list).toString();return json;
}
}
穿入参数,返回json字符串,相应的C++ 调用jni代码如下:
#include
#include
#include
#include "windows.h"
using namespace std;
#ifdef _WIN32
#define PATH_SEPARATOR ';'
#else
#define PATH_SEPARATOR ':'
#endif
jstring NewJString(JNIEnv env, LPCTSTR str);
string JStringToCString (JNIEnv *env, jstring str);
int main()
{
JavaVMOption options[3];
JNIEnv *env;
JavaVM *jvm;
JavaVMInitArgs vm_args;
long status;
jclass test,item,itemList;
jmethodID mid;
options[0].optionString = "-Djava.compiler=NONE";
options[1].optionString = "-Djava.class.path=.";
options[2].optionString = "-verbose:jni"; //用于跟踪运行时的信息
memset(&vm_args, 0, sizeof(vm_args));
vm_args.version = JNI_VERSION_1_6;
vm_args.nOptions = 1;
vm_args.options = options;
status = JNI_CreateJavaVM(&jvm, (void*)&env, &vm_args);if (status != JNI_ERR) { test = env->FindClass("com/iscas/test/Test"); item = env->FindClass("com/iscas/test/Item"); itemList = env->FindClass("com/iscas/test/ItemList"); if(test !=0 && item!=0) { mid = env->GetMethodID(test, "getItemList", "(ILjava/lang/String;F)Ljava/lang/String;"); if(mid != 0) { jobject obj_test = env->AllocObject(test); jobject obj_item = env->AllocObject(item); mid = env->GetMethodID(test,"getItemList","(ILjava/lang/String;F)Ljava/lang/String;"); jint instance_id = 10; const char arg[] = "jom"; jstring instance_name = NewJString(env, arg); jfloat instance_score = 98.5; jstring s = (jstring)env->CallObjectMethod(obj_test,mid,instance_id,instance_name,instance_score); cout<<s<<endl; string ss = JStringToCString(env,s); cout<<ss<<endl; } }
}
}
PS1:在工程目录下 com/iscas/test/ 路径下放置着 Test.class,Item.class,ItemList.class以及 gson-2.2.4.jar,jdom-2.0.5.jar,json-lib-2.4-jdk15.jar。
PS2:通过设置断点来看,
jstring s = (jstring)env->CallObjectMethod(obj_test,mid,instance_id,instance_name,instance_score);
这句话穿入的参数是正确的,返回的却为空。
还请各位大神不吝赐教!!