如何使用JNI创建对象?

14 浏览
0 Comments

如何使用JNI创建对象?

我需要使用NDK和JNI将一些函数实现到Android应用程序中。

这是我写的C代码,带有我的疑问:

#include 
#include 
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;
    
    // 我应该将什么作为第二个参数?根据 .java 文件中所提到的,我的尝试是否正确?我使用了这个文档:http://download.oracle.com/javase/6/docs/technotes/guides/jni/spec/functions.html#wp16027
    cls = (*env)->FindClass(env, "com/example/ndktest/NDKTest/Point");
    
    // http://download.oracle.com/javase/6/docs/technotes/guides/jni/spec/functions.html#wp16660
    // 再次问一下,最后一个参数是否正确?
    constructor = (*env)->GetMethodID(env, cls, "", "void(V)");
    
    // 我想将 "5" 和 "6" 分别赋给 point.x 和 point.y。
    object = (*env)->NewObject(env, cls, constructor, 5, 6);
    
    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 {
    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");
    }
}

当我尝试运行这段代码时,它无法工作。

0