如何传递字符串数组?
我发布了代码:
xx.cpp
JNIEXPORT jstring JNICALL Hello_Native(JNIEnv *env, jobject obj,jstring string)
{
const char *str = env->GetStringUTFChars(string, 0);
return env->NewStringUTF( "Hello from JNI !");
}
static JNINativeMethod gMethods[] = {
{"JniHello",const_cast<char*>("(Ljava/lang/jsting)Ljava/lang/jsting;"),(void*)Hello_Native}
xx.java
public native static String JniHello(String text);
系统始终提示在JniHello
中声明gMethods
并且参数不正确时出现问题。
答案 0 :(得分:2)
javah
会为您正确生成它。如果您的Java名称在类JniHello
中为MyHello
且您的包名为com.hello
,则JNICALL函数必须为Java_com_hello_MyHello_JniHello
。它不能是Hello_Native
,你已经成功了。JNINativeMethod
struct java/lang/jsting
这样的课程。如果我为您添加缺少的java/lang/jstring
,则甚至没有r
。您被要求提供JAVA签名,而不是JNI。所以它必须是java/lang/String
。javap -s
的输出您的代码还有一个问题:使用GetStringUTFChars
时,您还必须在返回之前调用`ReleaseStringUTFChars',否则您会发生泄漏。但你迟早会发现这个。
答案 1 :(得分:1)
的const_cast( “(Ljava /郎/ jsting)Ljava /郎/ jsting;”) 拼写错误,应该是 const_cast会( “(Ljava /郎/ jsting)Ljava /郎/的jstring;”)
jsting ==&gt;的jstring
答案 2 :(得分:1)
Copy some android source code to help you(JNI):
static jobject osNetworkSystem_getHostByNameImpl(JNIEnv* env, jclass clazz,
jstring nameStr, jboolean preferIPv6Addresses) {
}
static void osNetworkSystem_setInetAddressImpl(JNIEnv* env, jobject obj,
jobject sender, jbyteArray address) {
}
static jobject osNetworkSystem_inheritedChannelImpl(JNIEnv* env, jobject obj) {
}
/*
* JNI registration.
*/
static JNINativeMethod gMethods[] = {
/* name, signature, funcPtr */
{ "getHostByNameImpl", "(Ljava/lang/String;Z)Ljava/net/InetAddress;", (void*) osNetworkSystem_getHostByNameImpl },
{ "setInetAddressImpl", "(Ljava/net/InetAddress;[B)V", (void*) osNetworkSystem_setInetAddressImpl },
{ "inheritedChannelImpl", "()Ljava/nio/channels/Channel;", (void*) osNetworkSystem_inheritedChannelImpl },
};
int register_org_apache_harmony_luni_platform_OSNetworkSystem(JNIEnv* env) {
return jniRegisterNativeMethods(env,
"org/apache/harmony/luni/platform/OSNetworkSystem",
gMethods,
NELEM(gMethods));
}