gpt4 book ai didi

java - 如何使用 jni 构建项目,而无需构建过程重新创建 header ?

转载 作者:行者123 更新时间:2023-12-02 05:46:53 25 4
gpt4 key购买 nike

我在 Eclipse 中使用 JNI 教程:

https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html#zz-2.6

(我仅使用“Eclipse 中的 2.6 JNI”部分)。

该教程中的示例 (HelloJNI) 对我有用,也适用于我的项目。

然后我对头文件进行了一项更改 - 添加了以下行:

#include <vector>

并按照教程中的说明再次构建它:

Run the makefile for the target "all", by right-click on the makefile ⇒ Make >Targets ⇒ Build ⇒ Select the target "all" ⇒ Build

并且它用原来的头文件替换了我的头文件......

我不明白为什么会发生这种情况,因为目标 SPImageProc.h 的依赖是 SPImageProc.class ,而我没有更改 SPImageProc.class ,我只更改了 SPImageProc.h 。

开发环境

+面向 Java 开发人员的 Eclipse IDE(32 位)版本:Kepler Service Release 2。

+Eclipse 的 CDT 插件

+Windows 10 64位(我使用eclipse 32位,因为在某些时候,64位eclipse无法打开,解决方案是使用32位eclipse)

生成文件

# Define a variable for classpath
CLASS_PATH = ../bin

# Define a virtual path for .class in the bin directory
vpath %.class $(CLASS_PATH)

all : spimageproc.dll

# $@ matches the target, $< matches the first dependency
spimageproc.dll : SPImageProc.o
g++ -Wl,--add-stdcall-alias -shared -o $@ $<

# $@ matches the target, $< matches the first dependency
SPImageProc.o : SPImageProc.cpp SPImageProc.h
g++ -I"C:\Program Files (x86)\Java\jdk1.8.0_212\include" -I"C:\Program Files (x86)\Java\jdk1.8.0_212\include\win32" -c $< -o $@

# $* matches the target filename without the extension
SPImageProc.h : SPImageProc.class
javah -classpath $(CLASS_PATH) $*

clean :
rm SPImageProc.h SPImageProc.o spimageproc.dll

SPImageProc.h

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class SPImageProc */

#ifndef _Included_SPImageProc
#define _Included_SPImageProc
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: SPImageProc
* Method: cppFunc
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_SPImageProc_cppFunc
(JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

SPImageProc.cpp

#include <jni.h>
#include <stdio.h>
#include "SPImageProc.h"

JNIEXPORT void JNICALL Java_SPImageProc_cppFunc(JNIEnv *env, jobject thisObj) {
printf("After adding include vector to header !\n");
return;
}

SPImageProc.java

public class SPImageProc {

static {
System.loadLibrary("spimageproc"); // spimageproc.dll

}

// Declare native method
private native void cppFunc();

public static void function() {
new SPImageProc().cppFunc(); // Allocate an instance and invoke the native
// method
}
}

CBIR.java

public class CBIR {


public static void main(String[] args) {
SPImageProc.function();
}

}

编辑

这些是我想要使用的原始文件(它们是我决定使用 jni 的原因):

SPImageProc.cpp

#include <cstdlib>
#include <cassert>
#include <cstring>
#include <opencv2/xfeatures2d.hpp>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <cstdio>
#include "SPImageProc.h"
extern "C" {
#include "SPLogger.h"
}

using namespace cv;
using namespace std;

#define PCA_MEAN_STR "mean"
#define PCA_EIGEN_VEC_STR "e_vectors"
#define PCA_EIGEN_VAL_STR "e_values"
#define STRING_LENGTH 1024
#define WARNING_MSG_LENGTH 2048

#define GENERAL_ERROR_MSG "An error occurred"
#define PCA_DIM_ERROR_MSG "PCA dimension couldn't be resolved"
#define PCA_FILE_NOT_EXIST "PCA file doesn't exist"
#define PCA_FILE_NOT_RESOLVED "PCA filename couldn't be resolved"
#define NUM_OF_IMAGES_ERROR "Number of images couldn't be resolved"
#define NUM_OF_FEATS_ERROR "Number of features couldn't be resolved"
#define MINIMAL_GUI_ERROR "Minimal GUI mode couldn't be resolved"
#define IMAGE_PATH_ERROR "Image path couldn't be resolved"
#define IMAGE_NOT_EXIST_MSG ": Images doesn't exist"
#define MINIMAL_GUI_NOT_SET_WARNING "Cannot display images in non-Minimal-GUI mode"
#define ALLOC_ERROR_MSG "Allocation error"
#define INVALID_ARG_ERROR "Invalid arguments"





void sp::ImageProc::initFromConfig(const SPConfig config) {
SP_CONFIG_MSG msg = SP_CONFIG_SUCCESS;
pcaDim = spConfigGetPCADim(config, &msg);
if (msg != SP_CONFIG_SUCCESS) {
spLoggerPrintError(PCA_DIM_ERROR_MSG, __FILE__, __func__, __LINE__);
throw Exception();
}
numOfImages = spConfigGetNumOfImages(config, &msg);
if (msg != SP_CONFIG_SUCCESS) {
spLoggerPrintError(NUM_OF_IMAGES_ERROR, __FILE__, __func__, __LINE__);
throw Exception();
}
numOfFeatures = spConfigGetNumOfFeatures(config, &msg);
if (msg != SP_CONFIG_SUCCESS) {
spLoggerPrintError(NUM_OF_FEATS_ERROR, __FILE__, __func__, __LINE__);
throw Exception();
}
minimalGui = spConfigMinimalGui(config, &msg);
if (msg != SP_CONFIG_SUCCESS) {
spLoggerPrintError(MINIMAL_GUI_ERROR, __FILE__, __func__, __LINE__);
throw Exception();
}
}

void sp::ImageProc::getImagesMat(vector<Mat>& images, const SPConfig config) {
char warningMSG[WARNING_MSG_LENGTH] = { '\0' };
for (int i = 0; i < numOfImages; i++) {
char imagePath[STRING_LENGTH + 1] = { '\0' };
if (spConfigGetImagePath(imagePath, config, i) != SP_CONFIG_SUCCESS) {
spLoggerPrintError(IMAGE_PATH_ERROR, __FILE__, __func__, __LINE__);
throw Exception();
}
Mat img = imread(imagePath, IMREAD_GRAYSCALE);
if (img.empty()) {
sprintf(warningMSG, "%s %s", imagePath, IMAGE_NOT_EXIST_MSG);
spLoggerPrintWarning(warningMSG, __FILE__, __func__, __LINE__);
continue;
}
images.push_back(img);
}
}

void sp::ImageProc::getFeatures(vector<Mat>& images, Mat& features) {
//To store the keypoints that will be extracted by SIFT
vector<KeyPoint> keypoints;
//To store the SIFT descriptor of current image
Mat descriptor;
//To store all the descriptors that are extracted from all the images.

//The SIFT feature extractor and descriptor
Ptr<xfeatures2d::SiftDescriptorExtractor> detector =
xfeatures2d::SIFT::create(numOfFeatures);

//feature descriptors and build the vocabulary
for (int i = 0; i < static_cast<int>(images.size()); i++) {
//detect feature points
detector->detect(images[i], keypoints);
//compute the descriptors for each keypoint
detector->compute(images[i], keypoints, descriptor);
//put the all feature descriptors in a single Mat object
features.push_back(descriptor);
}
}

void sp::ImageProc::preprocess(const SPConfig config) {
try {
vector<Mat> images;
Mat features;
char pcaPath[STRING_LENGTH + 1] = { '\0' };
getImagesMat(images, config);
getFeatures(images, features);
pca = PCA(features, Mat(), CV_PCA_DATA_AS_ROW, pcaDim);
if (spConfigGetPCAPath(pcaPath, config) != SP_CONFIG_SUCCESS) {
spLoggerPrintError(PCA_FILE_NOT_RESOLVED, __FILE__, __func__,
__LINE__);
throw Exception();
}
FileStorage fs(pcaPath, FileStorage::WRITE);
fs << PCA_EIGEN_VEC_STR << pca.eigenvectors;
fs << PCA_EIGEN_VAL_STR << pca.eigenvalues;
fs << PCA_MEAN_STR << pca.mean;
fs.release();
} catch (...) {
spLoggerPrintError(GENERAL_ERROR_MSG, __FILE__, __func__, __LINE__);
throw Exception();
}
}

void sp::ImageProc::initPCAFromFile(const SPConfig config) {
if (!config) {
spLoggerPrintError(GENERAL_ERROR_MSG, __FILE__, __func__, __LINE__);
throw Exception();
}
char pcaFilename[STRING_LENGTH + 1] = { '\0' };
if (spConfigGetPCAPath(pcaFilename, config) != SP_CONFIG_SUCCESS) {
spLoggerPrintError(PCA_FILE_NOT_RESOLVED, __FILE__, __func__, __LINE__);
throw Exception();
}
FileStorage fs(pcaFilename, FileStorage::READ);
if (!fs.isOpened()) {
spLoggerPrintError(PCA_FILE_NOT_EXIST, __FILE__, __func__, __LINE__);
throw Exception();
}
fs[PCA_EIGEN_VEC_STR] >> pca.eigenvectors;
fs[PCA_EIGEN_VAL_STR] >> pca.eigenvalues;
fs[PCA_MEAN_STR] >> pca.mean;
fs.release();
}

sp::ImageProc::ImageProc(const SPConfig config) {
try {
if (!config) {
spLoggerPrintError(INVALID_ARG_ERROR, __FILE__, __func__, __LINE__);
throw Exception();
}
SP_CONFIG_MSG msg;
bool preprocMode = false;
initFromConfig(config);
if ((preprocMode = spConfigIsExtractionMode(config, &msg))) {
preprocess(config);
} else {
initPCAFromFile(config);
}
} catch (...) {
spLoggerPrintError(GENERAL_ERROR_MSG, __FILE__, __func__, __LINE__);
throw Exception();
}
}

SPPoint* sp::ImageProc::getImageFeatures(const char* imagePath, int index,
int* numOfFeats) {
vector<KeyPoint> keypoints;
Mat descriptor, img, points;
double* pcaSift = NULL;
char errorMSG[STRING_LENGTH * 2];
Ptr<xfeatures2d::SiftDescriptorExtractor> detector;
if (!imagePath || !numOfFeats) {
spLoggerPrintError(INVALID_ARG_ERROR, __FILE__, __func__, __LINE__);
return NULL;
}
img = imread(imagePath, IMREAD_GRAYSCALE);
if (img.empty()) {
sprintf(errorMSG, "%s %s", imagePath, IMAGE_NOT_EXIST_MSG);
spLoggerPrintError(errorMSG, __FILE__, __func__, __LINE__);
return NULL;
}
detector = xfeatures2d::SIFT::create(numOfFeatures);
detector->detect(img, keypoints);
detector->compute(img, keypoints, descriptor);
points = pca.project(descriptor);
pcaSift = (double*) malloc(sizeof(double) * pcaDim);
if (!pcaSift) {
spLoggerPrintError(ALLOC_ERROR_MSG, __FILE__, __func__, __LINE__);
return NULL;
}
*numOfFeats = points.rows;
SPPoint* resPoints = (SPPoint*) malloc(sizeof(*resPoints) * points.rows);
if (!resPoints) {
free(pcaSift);
spLoggerPrintError(ALLOC_ERROR_MSG, __FILE__, __func__, __LINE__);
return NULL;
}
for (int i = 0; i < points.rows; i++) {
for (int j = 0; j < points.cols; j++) {
pcaSift[j] = (double) points.at<float>(i, j);
}
resPoints[i] = spPointCreate(pcaSift, pcaDim, index);
}
free(pcaSift);
return resPoints;
}

void sp::ImageProc::showImage(const char* imgPath) {
if (minimalGui) {
Mat img = imread(imgPath, cv::IMREAD_COLOR);
if (img.empty()) {
spLoggerPrintWarning(IMAGE_NOT_EXIST_MSG, __FILE__, __func__,
__LINE__);
return;
}
imshow(windowName, img);
waitKey(0);
destroyAllWindows();
} else {
spLoggerPrintWarning(MINIMAL_GUI_NOT_SET_WARNING, __FILE__, __func__,
__LINE__);
}

}


SPImageProc.h

#ifndef SPIMAGEPROC_H_
#define SPIMAGEPROC_H_
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <vector>

extern "C" {
#include "SPConfig.h"
#include "SPPoint.h"
}

namespace sp {

/**
* A class which supports different image processing functionalites.
*/
class ImageProc {
private:
const char* windowName = "Software Project CBIR";
int pcaDim;
int numOfImages;
int numOfFeatures;
cv::PCA pca;
bool minimalGui;
void initFromConfig(const SPConfig);
void getImagesMat(std::vector<cv::Mat>&, const SPConfig);
void getFeatures(std::vector<cv::Mat>&,
cv::Mat&);
void preprocess(const SPConfig config);
void initPCAFromFile(const SPConfig config);
public:

/**
* Creates a new object for the purpose of image processing based
* on the configuration file.
* @param config - the configuration file from which the object is created
*/
ImageProc(const SPConfig config);

/**
* Returns an array of features for the image imagePath. All SPPoint elements
* will have the index given by index. The actual number of features extracted
* for this image will be stored in the pointer given by numOfFeats.
*
* @param imagePath - the target imagePath
* @param index - the index of the image in the database
* @param numOfFeats - a pointer in which the actual number of feats extracted
* will be stored
* @return
* An array of the actual features extracted. NULL is returned in case of
* an error.
*/
SPPoint* getImageFeatures(const char* imagePath,int index,int* numOfFeats);

/**
* Displays the image given by imagePath. Notice that this function works
* only in MinimalGUI mode (otherwise a warnning message is printed).
*
* @param imagePath - the path of the image to be displayed
*/
void showImage(const char* imagePath);
};

}
#endif

最佳答案

您提到更改“该”头文件,实际上您只提供了一个头文件,并且您的 makefile 仅引用了该头文件。该 header 是机器从您的类文件生成的,不应编辑,如顶部突出的注释所示。如果您以影响 native 接口(interface)的方式修改类,即添加或删除 native 方法或修改任何现有方法的签名,则需要重新生成它。

这就是为什么您复制的 Makefile 设置为在 Java 类文件发生更改时自动重建 header 的原因。当然,如果 Java 源代码发生更改,它还会自动重建类文件,我认为这不会是意外的情况。所以,

How to build project with jni without the building process recreating the header?

如果您不修改 Java 源代码或出于某种其他原因重建 Java 类,则不会重建 header 。您还可以删除 makefile 规则,该规则会导致在 Java 部分发生更改时重新构建它,但是您只需手动维护它,如果您通过运行 javah 来做到这一点,则通过这是最简单、最安全的选择——然后你就回到了开始的地方,但自动化程度较低。

此外,没有理由修改该 header 。它已经包含了其中声明所需的所有内容,因此您添加的任何内容都不会对其本身带来好处。您想要在 C 源代码中声明的任何其他内容都可以直接进入源代码本身,或者进入您手动创建和管理的单独 header 。

关于java - 如何使用 jni 构建项目,而无需构建过程重新创建 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56084307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com