<p>Andoird 中使用了一种不同传统Java JNI的方式来定义其native的函数。其中很重要的区别是Andorid使用了一种Java 和 C 函数的映射表数组,并在其中描述了函数的参数和返回值。这个数组的类型是JNINativeMethod,定义如下:</p> <p><wbr></p> <p>typedef struct {<br> <wbr><wbr><wbr>const char* name;<br> <wbr><wbr><wbr>const char* signature;<br> <wbr><wbr><wbr>void* <wbr><wbr><wbr><wbr><wbr><wbr>fnPtr;<br> } JNINativeMethod;</p> <p>第一个变量name是Java中函数的名字。</p> <p>第二个变量signature,用字符串是描述了函数的参数和返回值</p> <p>第三个变量fnPtr是函数指针,指向C函数。</p> <p><wbr></p> <p>其中比较难以理解的是第二个参数,例如</p> <p>"()V"</p> <p>"(II)V"</p> <p>"(Ljava/lang/String;Ljava/lang/String;)V"</p> <p><wbr></p> <p>实际上这些字符是与函数的参数类型一一对应的。</p> <p>"()" 中的字符表示参数,后面的则代表返回值。例如"()V" 就表示void Func();</p> <p>"(II)V" 表示 void Func(int, int);</p> <p><wbr></p> <p>具体的每一个字符的对应关系如下</p> <p><wbr></p> <p><strong>字符 <wbr><wbr><wbr><wbr>Java类型 <wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>C类型</strong></p> <p>V <wbr><wbr><wbr><wbr><wbr><wbr><wbr>void <wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>void<br> Z <wbr><wbr><wbr><wbr><wbr><wbr><wbr>jboolean <wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>boolean<br> I <wbr><wbr><wbr><wbr><wbr><wbr><wbr>jint <wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>int<br> J <wbr><wbr><wbr><wbr><wbr><wbr><wbr>jlong <wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>long<br> D <wbr><wbr><wbr><wbr><wbr><wbr><wbr>jdouble <wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>double<br> F <wbr><wbr><wbr><wbr><wbr><wbr><wbr>jfloat <wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>float<br> B <wbr><wbr><wbr><wbr><wbr><wbr><wbr>jbyte <wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>byte<br> C <wbr><wbr><wbr><wbr><wbr><wbr><wbr>jchar <wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>char<br> S <wbr><wbr><wbr><wbr><wbr><wbr><wbr>jshort <wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>short</p> <p><wbr></p> <p>数组则以"["开始,用两个字符表示</p> <p><wbr></p> <p>[I <wbr><wbr><wbr><wbr><wbr><wbr>jintArray <wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>int[]<br> [F <wbr><wbr><wbr><wbr><wbr><wbr>jfloatArray <wbr><wbr><wbr><wbr><wbr>float[]<br> [B <wbr><wbr><wbr><wbr><wbr><wbr>jbyteArray <wbr><wbr><wbr><wbr><wbr><wbr>byte[]<br> [C <wbr><wbr><wbr><wbr><wbr><wbr>jcharArray <wbr><wbr><wbr><wbr><wbr><wbr>char[]<br> [S <wbr><wbr><wbr><wbr><wbr><wbr>jshortArray <wbr><wbr><wbr><wbr><wbr>short[]<br> [D <wbr><wbr><wbr><wbr><wbr><wbr>jdoubleArray <wbr><wbr><wbr><wbr>double[]<br> [J <wbr><wbr><wbr><wbr><wbr><wbr>jlongArray <wbr><wbr><wbr><wbr><wbr><wbr>long[]<br> [Z <wbr><wbr><wbr><wbr><wbr><wbr>jbooleanArray <wbr><wbr><wbr>boolean[]</p> <p><wbr></p> <p>上面的都是基本类型。如果Java函数的参数是class,则以"L"开头,以";"结尾中间是用"/" 隔开的包及类名。而其对应的C函数名的参数则为jobject. 一个例外是String类,其对应的类为jstring</p> <p><wbr></p> <p>Ljava/lang/String; <wbr><wbr><wbr><wbr><wbr>String <wbr><wbr><wbr><wbr><wbr><wbr><wbr>jstring<br> Ljava/net/Socket; <wbr><wbr><wbr><wbr><wbr>Socket <wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>jobject</p> <p><wbr></p> <p>如果JAVA函数位于一个嵌入类,则用$作为类名间的分隔符。</p> <p>例如 "(Ljava/lang/String;Landroid/os/FileUtils$FileStatus;)Z"</p> <p><br> </p>