我正在研究android-ndk,其中我尝试将字符串从我的C代码传递到我的java然后在活动中。我的代码如下,但我收到以下错误。请帮帮我
#include <com_testing_ndk_FibLib.h>
JNIEXPORT jstring JNICALL Java_Sample1_stringMethod(JNIEnv *env, jobject obj,
jstring string) {
const char *name = (*env)->GetStringUTFChars(string, NULL); //Java String to C Style string
char msg[60] = "HelloWorld";
jstring result;
strcat(msg, name);
(*env)->ReleaseStringUTFChars(string, name);
puts(msg);
result = (*env)->NewStringUTF(msg); // C style string to Java String
return result;
}
错误日志:
jni/com_testing_ndk_FibLib.c: In function 'Java_Sample1_stringMethod':
jni/com_testing_ndk_FibLib.c:7:55: error: 'NULL' undeclared (first use in this function)
const char *name = (*env)->GetStringUTFChars(string, NULL); //Java String to C Style string
^
jni/com_testing_ndk_FibLib.c:7:55: note: each undeclared identifier is reported only once for each function it appears in
jni/com_testing_ndk_FibLib.c:7:21: error: too few arguments to function '(*env)->GetStringUTFChars'
const char *name = (*env)->GetStringUTFChars(string, NULL); //Java String to C Style string
^
jni/com_testing_ndk_FibLib.c:11:2: warning: incompatible implicit declaration of built-in function 'strcat'
strcat(msg, name);
^
jni/com_testing_ndk_FibLib.c:12:2: warning: passing argument 2 of '(*env)->ReleaseStringUTFChars' discards 'const' qualifier from pointer target type
(*env)->ReleaseStringUTFChars(string, name);
^
jni/com_testing_ndk_FibLib.c:12:2: note: expected 'jstring' but argument is of type 'const char *'
jni/com_testing_ndk_FibLib.c:12:2: error: too few arguments to function '(*env)->ReleaseStringUTFChars'
jni/com_testing_ndk_FibLib.c:14:11: warning: passing argument 1 of '(*env)->NewStringUTF' from incompatible pointer type
result = (*env)->NewStringUTF(msg); // C style string to Java String
^
jni/com_testing_ndk_FibLib.c:14:11: note: expected 'const struct JNINativeInterface **' but argument is of type 'char *'
jni/com_testing_ndk_FibLib.c:14:11: error: too few arguments to function '(*env)->NewStringUTF'
make: *** [obj/local/arm64-v8a/objs/com_testing_ndk_FibLib/com_testing_ndk_FibLib.o] Error 1
我的Java代码:
public class FibLib {
static {
System.loadLibrary("com_testing_ndk_FibLib");
}
public static native String stringMethod(String text);
public static void main(String[] args)
{
System.loadLibrary("Sample1");
FibLib sample = new FibLib();
String text = sample.stringMethod("world");
System.out.println("stringMethod: " + text);
}
}
答案 0 :(得分:1)
当您编译C代码时,所有JNI调用都缺少第一个应该是env
的参数。
如果您的代码使用的是C ++,则可以调用env->NewStringUTF("xx")
之类的调用。但是在C中,JNIEnv *不是一个对象,因此你必须将它作为第一个参数传递,如下所示:(*env)->NewStringUTF(env, "xx")
对于未定义的NULL,您可以通过包含定义它的标头来解决此问题:#include <stddef.h>
答案 1 :(得分:0)
第二个参数似乎不是可选的:
jboolean iscopy;
const char *name = (*env)->GetStringUTFChars(string, &iscopy);