【发布时间】:2014-12-12 21:15:28
【问题描述】:
在 32 位 Ubuntu 机器上,从 JDK 1.7.0 开始,我无法打印宽字符。
这是我的代码:
JNIFoo.java
public class JNIFoo {
public native void nativeFoo();
static {
System.loadLibrary("foo");
}
public void print () {
nativeFoo();
System.out.println("The end");
}
public static void main(String[] args) {
(new JNIFoo()).print();
return;
}
}
foo.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <jni.h>
#include "JNIFoo.h"
JNIEXPORT void JNICALL Java_JNIFoo_nativeFoo (JNIEnv *env, jobject obj)
{
fwprintf(stdout, L"using fWprintf\n");
fflush(stdout);
}
然后我正在执行以下命令:
javac JNIFoo.java
javah -jni JNIFoo
gcc -shared -fpic -o libfoo.so -I/path/to/jdk/include -I/path/to/jdk/include/linux foo.c
以下是根据用于执行程序的 JDK 的结果:
jdk1.6.0_45/bin/java -Djava.library.path=/path/to/jni_test JNIFoo
使用 fWprintf
结束
jdk1.7.0/bin/java -Djava.library.path=/path/to/jni_test JNIFoo
结束
jdk1.8.0_25/bin/java -Djava.library.path=/path/to/jni_test JNIFoo
结束
如您所见,对于 JDK 1.7 和 JDK 1.8,fwprintf 无效!
所以我的问题是我缺少什么能够使用 JDK 1.7(和 1.8)使用宽字符?
注意:如果我调用fprintf而不是fwprintf,那么没有问题,一切都正确打印出来。
编辑
根据James的评论,我创建了一个main.c文件:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <wchar.h>
#include "JNIFoo.h"
int main(int argc, char* argv[])
{
fwprintf(stdout, L"In the main\n");
Java_JNIFoo_nativeFoo(NULL, NULL);
return 0;
}
然后我这样编译:
gcc -Wall -L/path/to/jni_test -I/path/to/jdk1.8.0_25/include -I/pat/to/jdk1.8.0_25/include/linux main.c -o main -lfoo
并设置 LD_LIBRARY_PATH
export LD_LIBRARY_PATH=/path/to/jni_test
而且它工作正常:
In the main
using fWprintf
所以问题可能不是来自C。
注意:它在 64 位机器上正常工作。 我在使用 linux Mint 32 位时遇到了类似的问题。
【问题讨论】:
-
也许打印/确定来自
fwprintf()的int返回值可能会有所启发? -
你需要什么
fwprintf()?fprintf(stdout, ”%Ls", L"using fWprintf\n");怎么了? -
@chux fwprintf() 返回 -1(jdk 1.7.0 和 1.8.0)。 errno 没有错误。 ferror 没问题。
-
@AlexCohn 这就是我们程序的工作方式。我的问题中的代码只是我简化的一些代码。
-
@dalf 所以至少
fwprintf()与 return -1 一致,并且不打印“fwprintf 函数返回传输的宽字符数,如果发生输出或编码错误,则返回负值”。嗯嗯。
标签: c java-native-interface widechar