我编写了一个小型 C 库,用于从 DLL 中提取信息( key )。
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 绑定(bind)如下所示:
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);
}
}
每当我调用 getKeyP
和 getKeyL
时,都会抛出异常
我尝试将参数类型从 byte[]
更改为 Pointer
以及 ByteBuffer
,并且还尝试 extend
ing 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);
}
现在它按预期工作了(-:
关于java - JNA:无效的内存访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46556738/