简体   繁体   中英

Java JNA can't write float to memory

I'm trying to write a float to memory but It's not working.

Kernel32.java

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

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.

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. A float is typically at least 4 bytes ( Float.SIZE / 8 bytes in Java), so you'd need to adjust your offset. 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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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