JNI中文处理问题小结
2007-03-15 21:53:28 来源:WEB开发网核心提示: 如果你愿意,给JNIString再加个JNIString(JNIEnv* env, const wstring& str)和一个operator =(const wstring& rhs)操作符重载就比较完美了,JNI中文处理问题小结(4),:),很简单,留给用得到的朋友自己加吧,下面是一
如果你愿意,给JNIString再加个JNIString(JNIEnv* env, const wstring& str)和一个operator =(const wstring& rhs)操作符重载就比较完美了,:),很简单,留给用得到的朋友自己加吧。
下面是一个使用该类的例子(真正跟用于演示的code很少,大部分都是些routine code,:)):
#include <iostream>
#include <string>
#include <assert.h>
#include <jni.h>
using namespace std;
int main() {
int res;
JavaVM* jvm;
JNIEnv* env;
JavaVMInitArgs vm_args;
JavaVMOption options[3];
options[0].optionString = "-Djava.compiler=NONE";
options[1].optionString = "-Djava.class.path=.;.."; // .. is specially for this project
options[2].optionString = "-verbose:jni";
vm_args.version = JNI_VERSION_1_4;
vm_args.nOptions = 3;
vm_args.options = options;
vm_args.ignoreUnrecognized = JNI_TRUE;
res = JNI_CreateJavaVM (& jvm, (void* * )& env, & vm_args);
if (res < 0) {
fprintf (stderr, "Can''t create Java VM
");
return 1;
}
jclass cls = env->FindClass ("jni/test/Demo");
assert (0 != cls);
jmethodID mid = env->GetMethodID (cls, "", "(Ljava/lang/String;)V");
assert (0 != mid);
wchar_t* p = L"中国";
jobject obj = env->NewObject (cls, mid, env->NewString (reinterpret_cast (p), wcslen (p)));
assert (0 != obj);
mid = env->GetMethodID (cls, "getMessage", "()Ljava/lang/String;");
assert (0 != mid);
jstring str = (jstring)env->CallObjectMethod (obj, mid);
// use JNIString for easier handling.
JNIString jnistr (env, str);
cout << "JNIString:" << jnistr.GetString () << endl;
jnistr = "中文";
cout << jnistr.GetString () << endl;
jvm->DestroyJavaVM ();
fprintf (stdout, "Java VM destory.
");
return 0;
}
更多精彩
赞助商链接