'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);
}


Solution 1:[1]

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]);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1