簡體   English   中英

在JNA中獲取參數返回的不透明結構

[英]Getting an opaque struct returned by parameter in JNA

我試圖在Apple的Security.h框架中調用一個通過引用返回結構的方法,如下所示:

int findSomething(SomeStruct *s)

(具體而言,它的這種方法 ,而我試圖獲得itemRef 。有一個使用示例在這里 。)的問題是,我不知道哪些字段SomeStruct有或有多大是。 僅存在要傳遞給其他本機庫函數的情況。 所以,我想要這樣的東西(Java):

interface SomeLib extends Library {
    int findSomething(Pointer p);
}

...
Pointer p = ... // Not sure how to make this
nativeLib.findSomething(p)
// Do something with p

我想,如果我可以在Java中執行sizeof(SomeStruct) ,則可以使用JNAs Memory創建指針。 我可以編寫一個本機方法來返回sizeof(SomeStruct) ,但是我不想在自己的代碼中添加本機組件。

這類似於此問題 ,但是它詢問在運行時知道SomeStruct的字段的情況,而在我的情況下,庫作者有意遮蓋了這些字段。

SecKeychainItemRef類型定義為指向 struct的指針 這意味着SecKeychainFindGenericPassword函數實際上希望將指向該指針的指針作為itemRef參數,因此,可以將JNA PointerByReference類用作該參數。

成功調用之后,可以使用PointerByReference.getValue()獲取不透明指針。

/* int SecKeychainFindGenericPassword(
 *     Pointer keychainOrArray,
 *     int serviceNameLength,
 *     String serviceName,
 *     int accountNameLength,
 *     String accountName,
 *     IntByReference *passwordLength,
 *     PointerByReference passwordData,
 *     PointerByReference itemRef
 * );
 */

static void main() {
    IntByReference passLength = new IntByReference(0);
    PointerByReference passwordData = new PointerByReference();
    PointerByReference itemRef = new PointerByReference();

    int result = SecKeychainFindGenericPassword(
        keychainOrArray,
        "service name".length(),
        "service name",
        "account".length(),
        "account",
        passLength,
        passwordData,
        itemRef
    );

    if (result == 0) {
        System.out.printf(
            "OSStatus: %d, passDataPtr: 0x%08X, itemRefPtr: 0x%08X%n",
            result,
            Pointer.nativeValue(passwordData.getValue()),
            Pointer.nativeValue(itemRef.getValue())
        );
    } else {
        /* Use SecCopyErrorMessageString to get a human-readable message */
        System.out.printf("An error occurred: %d%n", result);
    }
}

如果在實際項目中調用此方法,建議創建一個名為SecKeychainItemRef的類,該類擴展了PointerByReference類。 即使不允許您訪問結構的內部結構,這也以更清晰的方式將參數的類型傳達給讀者。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM