[英]JNI Java using DLL function which takes an object as param
我需要使用一個外部的、未知的 DLL 並圍繞它構建一個 java 包裝器。 我目前沒有 DLL 和頭文件,甚至可能不會得到頭文件,但我想自己做好准備。 (我沒有使用 C++ 的經驗)
以下情況:
假設這個 DLL 有一個函數,它包含一個或多個 C++ 類作為方法簽名。 那么我怎么能用 JNI 調用這個函數,因為在我的 java 項目中,DLL 中的那些自定義類是不存在的? 是否可以選擇將 C++ 類“克隆”或“移植”到 Java? 我可以用像 Dependency Walker 這樣的工具來解決這個問題嗎?
實現這一目標的最佳/最簡單的方法是什么?
這是我已經嘗試過的一些代碼,以了解它的行為方式:
Java 類與主要
public class FourthJNI {
public static native int returnAgeOfHuman(int zuQuadrierendeZahl);
public static void main(String[] args) {
// /* This message will help you determine whether
// LD_LIBRARY_PATH is correctly set
// */
// System.out.println("library: "
// + System.getProperty("java.library.path"));
Human testHuman = new Human("abcde", 23, "M");
/* Call to shared library */
int ageOfHuman = FourthJNI.returnAgeOfHuman(5);
System.out.println(testHuman.toString());
System.out.println("Age: " + ageOfHuman);
}
}
生成 h 文件
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class FourthJNI */
#ifndef _Included_FourthJNI
#define _Included_FourthJNI
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: FourthJNI
* Method: returnAgeOfHuman
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_FourthJNI_returnAgeOfHuman
(JNIEnv *, jclass, jint);
#ifdef __cplusplus
}
#endif
#endif
這里最好的方法是使用適配器模式( https://en.wikipedia.org/wiki/Adapter_pattern )。 在JNI
代碼中,您必須按照C++
API 的預期,通過創建所有對象來調用DLL
。
您可以在這里找到示例: http : //jnicookbook.owsiak.org/recipe-No-021/和這里https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo025
您還可以查看一個共享庫 ( JNI
) 從另一個共享庫調用代碼的代碼: http : //jnicookbook.owsiak.org/recipe-No-023/
基本上,你所要做的是創建JNI
基於包裝,轉換代碼Java
調用本地方法為C++
調用,反之亦然-即轉化返回值到的東西,是由預計的Java代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.