javacallbackjava-native-interfaceffiproject-panama

Callback function's byte parameter has value out of bounds in project Panama function interface


I'm using the new Foreign function & memory API which is part of project Panama and available in preview in JAVA 19.

This is a simple Java callback function

public static byte addFive(byte t) {
    Byte test = (Byte) t;
    return (byte) (Long.valueOf(test) + 5);
}

I have a native library function that is called with parameters addFive and (byte) -41.

uint8_t callback_test(uint8_t (*fn)(uint8_t), uint8_t arg) {
    uint8_t res = fn(arg + 1) * 2;
    return res;
}

I expect t to have value -40, and this does show in the Intellij debugger. But when you print it, it prints 216 instead. In addition, casting to Byte gives an ArrayIndexOutOfBoundsException.

I do realize that the native function is an unsigned int, so the returned value of 216 makes sense. However, a java byte should not be allowed that value, so, I expect java to automatically convert it to -41.

Is this behavior expected?

What is the correct way to get the unsigned int from the native code passed to the java function as a byte in the range [-128, 127]?


Solution

  • There was a bug in JDK19 such that there was no value normalization in upcalls.

    This is now fixed.