如何在MainActivity上调用ndk函数

时间:2017-08-11 19:01:34

标签: java android android-ndk java-native-interface

我已经设法编译了以下代码,我想知道它是否很好,并且你给我一个如何在android的MainActivity中调用压缩器函数的例子。

#include <jni.h>
#include<Principal.h>

JNIEXPORT jint JNICALL 
JAVA_com_pfc_camera_ndkmain_MainActivity_compresion(JNIEnv* env,jobjectArray 
 jargv){


 //jargv is a Java array of Java strings
 int argc = env->GetArrayLength(jargv);
 typedef char *pchar;
 pchar *argv = new pchar[argc];
 int i;
for(i=0; i<argc; i++)
{
    jstring js = (jstring)env->GetObjectArrayElement(jargv, i); //A Java string
    const char *pjc = env->GetStringUTFChars(js,NULL); //A pointer to a Java-managed char buffer
    size_t jslen = strlen(pjc);
    argv[i] = new char[jslen+1]; //Extra char for the terminating null
    strcpy(argv[i], pjc); //Copy to *our* buffer. We could omit that, but IMHO this is cleaner. Also, const correctness.
    env->ReleaseStringUTFChars(js, pjc);
}

//Call main

Principal *pa=Principal::CreateInstance(argc,argv);
pa->Run();
pa->FreeInstance();

//main(argc, argv);

//Now free the array
for(i=0;i<argc;i++)
    delete [] argv[i];
delete [] argv;

return 0;


}

1 个答案:

答案 0 :(得分:0)

您必须实现Java端来调用代码的C端。 但我认为你的C代码缺少jclass参数。 您应该使用javah创建包含本机函数擦除的.h文件。请参阅documentation

Java方面应如下所示:

package com.pfc.camera.ndkmain;

public class MainActivity extends Activity {

    native int compression(String[] argv);

    public int foo(String[] args) {
        return compression(args);
    }
}