我需要使用NDK以及JNI将一些功能实现到Android应用程序中。
这是我所写的C代码:
#include <jni.h>
#include <stdio.h>
jobject
Java_com_example_ndktest_NDKTest_ImageRef(JNIEnv* env, jobject obj, jint width, jint height, jbyteArray myArray)
{
jint i;
jobject object;
jmethodID constructor;
jobject cls;
cls = (*env)->FindClass(env, "com/example/ndktest/NDKTest/Point");
//what should put as the second parameter? Is my try correct, according to what
//you can find in .java file? I used this documentation: http://download.oracle.com/javase/6/docs/technotes/guides/jni/spec/functions.html#wp16027
constructor = (*env)->GetMethodID(env, cls, "<init>", "void(V)");
//http://download.oracle.com/javase/6/docs/technotes/guides/jni/spec/functions.html#wp16660
//Again, is the last parameter ok?
object = (*env)->NewObject(env, cls, constructor, 5, 6);
//I want to assign "5" and "6" to point.x and point.y respectively.
return object;
}
我的问题或多或少在代码内得到了解释。也许还可以:函数(jobject)的返回类型可以吗?
现在,NDKTest.java:
package com.example.ndktest;
import android.app.Activity;
import android.widget.TextView;
import android.os.Bundle;
public class NDKTest extends Activity {
/** Called when the activity is first created. */
public native Point ImageRef(int width, int height, byte[] myArray);
public class Point
{
Point(int myx, int myy)
{
x = myx;
y = myy;
}
int x;
int y;
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
byte[] anArray = new byte[3];
for (byte i = 0; i < 3; i++)
anArray[i] = i;
Point point = ImageRef(2, 3, anArray);
tv.setText(String.valueOf(point.x));
setContentView(tv);
}
static
{
System.loadLibrary("test");
}
}
当我尝试运行代码时,它不起作用。
既然Point
是内部类,那么获得它的方法就是
jclass cls = (*env)->FindClass(env, "com/example/ndktest/NDKTest$Point");
$
内部类的约定在权威规范中并未真正明确记录,但根深蒂固于大量工作代码中,因此不太可能更改。但是,如果您限制JNI代码与顶级类一起使用,那会感觉有些健壮。
您需要一个以两个int作为参数的构造函数。的签名是(II)V
,因此:
constructor = (*env)->GetMethodID(env, cls, "<init>", "(II)V");
下次,在代码中包含一些错误处理,这样您就可以知道其中哪些部分不起作用!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句