android NDK --将C++方法转换为Java MTHOD

android NDK --converting C++ method to java mthod

本文关键字:转换 Java MTHOD 方法 C++ NDK android      更新时间:2023-10-16

我正在开发一个安卓应用程序,可以从任何捕获的图像中提取单词袋我将在本教程中使用 opencv 库

来实现此目的

现在我有一个C++的方法: void extractTrainingVocabulary(const path& basepath) {...}我在我的安卓活动中需要它

   void extractTrainingVocabulary(const path& basepath) {
for (directory_iterator iter = directory_iterator(basepath); iter
        != directory_iterator(); iter++) {
    directory_entry entry = *iter;
    if (is_directory(entry.path())) {
        cout << "Processing directory " << entry.path().string() << endl;
        extractTrainingVocabulary(entry.path());
    } else {
        path entryPath = entry.path();
        if (entryPath.extension() == ".jpg") {
            cout << "Processing file " << entryPath.string() << endl;
            Mat img = imread(entryPath.string());
            if (!img.empty()) {
                vector<KeyPoint> keypoints;
                detector->detect(img, keypoints);
                if (keypoints.empty()) {
                    cerr << "Warning: Could not find key points in image: "
                            << entryPath.string() << endl;
                } else {
                    Mat features;
                    extractor->compute(img, keypoints, features);
                    bowTrainer.add(features);
                }
            } else {
                cerr << "Warning: Could not read image: "
                        << entryPath.string() << endl;
            }
        }
    }
}
}

所以按照android NDK教程我应该像这样声明此方法:public native void extractTrainingVocabulary () ;

我的问题是如何处理C++参数const path& basepath? 如何在java方法中传递此参数

我希望我的问题对你来说很清楚谢谢

第一个问题是,C/C++ 代码中path的基本类型是什么,例如,如果这是 String,所以你需要用 String 值作为输入来声明 Java 方法。

class Dude{
public native void extractTrainingVocabulary(final String arg);
}

首先用javac Dude.java编译 Dude 类然后你需要头文件,将生成的类文件传递给javah Dude,然后javah会给你一个头文件,像这样。

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Dude */
#ifndef _Included_Dude
#define _Included_Dude
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     Dude
 * Method:    extractTrainingVocabulary
 * Signature: (Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_Dude_extractTrainingVocabulary
  (JNIEnv *, jobject, jstring);
#ifdef __cplusplus
}
#endif
#endif

在上面的代码中,jstring指向该方法的 Java 输入参数,您可能需要使用那个家伙。下一步是实现 Java_Dude_extractTrainingVocabulary 函数并调用实际方法。