简体   繁体   English

Java JNA 无法将浮点数写入内存

[英]Java JNA can't write float to memory

I'm trying to write a float to memory but It's not working.我正在尝试将浮点数写入内存,但它不起作用。

Kernel32.java kernel32.java

public abstract boolean WriteProcessMemory(Pointer paramPointer1, long paramLong, Pointer paramPointer2, int paramInt, IntByReference paramIntByReference);

MemoryWriting.java MemoryWriting.java

public void writeMemory(int address, float[] data) {
    int size = data.length;

    Memory toWrite = new Memory(size);

    for (int i = 0; i < size; i++) {
        toWrite.setFloat(i, data[i]);
    }

    kernel32.WriteProcessMemory(process, address, toWrite, size, null);
}

EDIT:编辑:

still same issue还是同样的问题

public void writeMemory(int address, float[] data) {
    int size = data.length;

    Memory toWrite = new Memory(size);

    for (int i = 0; i < size; i++) {
        toWrite.setFloat(i * Float.SIZE / 8, data[i]);
    }

    kernel32.WriteProcessMemory(process, address, toWrite, size, null);
}

It's easier if you make your own method signature that takes the float[] directly.如果您自己制作直接采用float[]的方法签名,则会更容易。

public interface MyKernel32 extends Kernel32 {
    MyKernel32 INSTANCE = Native.loadLibrary("kernel32", W32APIOptions.DEFAULT_OPTIONS);
    void WriteProcessMemory(HANDLE hProcess, Pointer address, float[] data, int size, Pointer blah);
}

EDIT编辑

You're writing float values at 1-byte increments.您正在以 1 字节的增量写入浮点值。 A float is typically at least 4 bytes ( Float.SIZE / 8 bytes in Java), so you'd need to adjust your offset.浮点数通常至少为 4 个字节(Java 中的Float.SIZE / 8个字节),因此您需要调整偏移量。 I really recommend using the function mapping, but if you insist in the extra overhead of copying the array to memory and then copying the memory buffer to process memory, you need to do this:真的推荐使用函数映射,但是如果你坚持将数组复制到内存然后将内存缓冲区复制到进程内存的额外开销,你需要这样做:

Memory m = ...;
float[] data = ...;
for(int i=0;i < data.length;i ++) {
    m.setFloat(i * Float.SIZE/8, data[i]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM