User
User

Reputation: 91

Map C++ structure to Java Structure

I am trying to call C++ function present within a dll file,C++ function takes structure object as parameter and function will assign values to it. I am making use this through Java native calls and my program is below,

public class WTS_CLIENT_ADDRESS extends Structure {
    public static class ByReference extends WTS_CLIENT_ADDRESS implements Structure.ByReference {

    }
public int AddressFamily;

public byte[] Address = new byte[20];

public WTS_CLIENT_ADDRESS() {
}

public WTS_CLIENT_ADDRESS(Pointer p) {
    super(p);
}

public byte[] getByteArray() {
    return Address;
}

@Override
protected List getFieldOrder() {
    return Arrays.asList("AddressFamily", "Address");
}
} 

I am getting values for the AddressFamily correctly but not for the Address. looks like something going wrong in the data structure between the byte array in c++ and the java structure byte array defined. Any help ?

The C++ structure for it is,

typedef struct _WTS_CLIENT_ADDRESS {
  DWORD AddressFamily;
  BYTE  Address[20];
} WTS_CLIENT_ADDRESS, *PWTS_CLIENT_ADDRESS;

Upvotes: 2

Views: 313

Answers (2)

Joe
Joe

Reputation: 341

What if you pass a single byte to java? There are two possible problems: Array and Type or maybe both of them. if a single byte can be passed to Java with no problem, then try to use BYTE *Address instead of BYTE Address[]. If it does not help, try to pass an array of chars instead of byte char Address[] or char *Address. Let me know if it's resolved.

Upvotes: 0

flyx
flyx

Reputation: 39678

In C++, static-length arrays declared in a struct are inlined into the struct. So your C++ code is, structure-wise, roughly equivalent to:

typedef struct _WTS_CLIENT_ADDRESS {
  DWORD AddressFamily;
  BYTE Address1;
  BYTE Address2;
  // ...
  BYTE Address20;
} WTS_CLIENT_ADDRESS;

Which is, to my knowledge, the only way you will be able to map Address in Java, since there is no better mapping from Java arrays to C++ array fields. Note that this differs from C++ array parameters in functions, which are basically pointers and therefore work properly.

Upvotes: 1

Related Questions