javajava-native-interfacejnajnaeratorbridj

BridJ type mapping for unsigned types


When generating BridJ code with JNAerator, it maps unsigned types (for example windows' ULONG) to a normal Java long:

// c code
typedef struct _S {
  USHORT    a;
  ULONG     b;
  ULONG64   c;
} S;


// generated java code
class S extends StructObject {

@Field(0)
public short a() {
    return this.io.getShortField(this, 0);
}

@Field(0)
S setA(short a) {
    this.io.setShortField(this, 0, a);
    return this;
}

@CLong
@Field(1)
public long b() {
    return this.io.getCLongField(this, 2);
}

@CLong
@Field(1)
S setB(long b) {
    this.io.setCLongField(this, 2, b);
    return this;
}

// ULONG64 is ignored and not generated at all

However, Java types are signed, not unsigned. If I need to correct that manually, which types do I need to use? Byte arrays like so?

@Field(0)
public byte[] a() { ... };

@Field(0)
public byte[] setA(byte[] a) { // check correct length };

Solution

  • Signed and unsigned types have the same size, just different semantics. You should definitely use the types chosen by JNAerator, and use Java primitives that deal with unsigned types such as the ones introduced in Java 8 (for instance, Integer.divideUnsigned).

    If Java 8 is not an option for you, you can just use casts and manipulate bits wisely.