簡體   English   中英

JNA:無效的內存訪問

[英]JNA: Invalid memory access

我編寫了一個小的C庫,該庫從DLL中提取信息(鍵)。

GetKey.h

#pragma once

#include <stdint.h>

#define getKey(x) getKeyL(x)
#define getKey(x,y) getKeyP(x,y)

void __declspec(dllexport) getKeyP(char *path, uint8_t key[]);
void __declspec(dllexport) getKeyL(uint8_t key[]);

GetKey.c

#include "getkey.h"

#include <stdio.h>
#include <string.h>
#include <windows.h>

void __declspec(dllexport) getKeyP(char *path, uint8_t key[])
{
    int lib = LoadLibraryA((path != NULL) ? path : "myLib");
    ((void(*)(void))(lib + 0x1340))();
    lib += 0x14020;

    for (int i = 0; i < 8; ++i)
    {
        key[i] = *(uint8_t*)(lib + (i << 4));
    }

    FreeLibrary(lib);
}

void __declspec(dllexport) getKeyL(uint8_t key[])
{
    getKeyP(NULL, key);
}

我的Java綁定如下所示:

public class GetKey
{
    private static final GetKeyBinding INSTANCE;

    static
    {
        System.setProperty("jna.library.path", "lib/dll/");

        GetKeyBinding lib;

        try
        {
            lib = Native.loadLibrary("x86_64/GetKey.dll", GetKeyBinding.class);
        } 
        catch (UnsatisfiedLinkError e)
        {
            try
            {
                lib = Native.loadLibrary("i386/GetKey.dll", GetKeyBinding.class);
            } 
            catch (UnsatisfiedLinkError f)
            {
                System.err.println("Failed to load library");
                lib = null;
            }
        }

        INSTANCE = lib;
    }

    public static void getKey(byte[] path, byte[] key)
    {
        INSTANCE.getKeyP(path, key);
    }

    public static void getKey(byte[] key)
    {
        INSTANCE.getKeyL(key);
    }

    private static interface GetKeyBinding extends Library
    {
        void getKeyP(byte[] path, byte[] key);
        void getKeyL(byte[] key);
    }
}

每當我調用getKeyPgetKeyL時,都會拋出異常,我嘗試將參數類型從byte[]更改為Pointer以及ByteBuffer ,並且還嘗試extend StdCallLibrary (起初對我來說意義不大) ,但是嘗試它永遠不會受到傷害,可以嗎?)仍然會得到異常……而且我知道代碼是可行的,因為我為此編寫了一個小型測試應用程序:

#include <stdio.h>
#include "GetKey.h"


int main()
{
    uint8_t key[8];
    getKeyP(NULL, key);

    for (int i = 0; i < 8; ++i)
    {
        printf("%02X ", key[i]);
    }
    getchar();
    return 0;
}

它將完全按照我的期望打印到控制台上...任何幫助都將不勝感激!

編輯:
我像這樣從Java調用我的函數:

byte[] key = new byte[8];
GetKey.getKey(key);

將調試器附加到我的DLL並進行調試后,我發現該異常的原因是在預期的字符串之后傳遞了“垃圾”字符。 我通過更改Java代碼來解決此問題:

public static void getKey(String path, byte[] key)
{
    INSTANCE.getKeyP((path + '\0').getBytes(), key);
}

現在它可以按預期工作(-:

暫無
暫無

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

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