简体   繁体   中英

Mapping forBSTR data type in JNA

in header file of DLL I need to wrap is used BSTR data type as I/O parameter. I need to create its mapping in JNA. I have found following example:

class BSTR extends PointerType {
  public BSTR() { }
  public BSTR(String value) {
    super(new Memory(value.length()*2+6).share(4));  
    getPointer().setInt(-4, value.length()*2);
    getPointer().setString(0, value, true);
 }
 public String toString() {
    int length = getPointer().getInt(-4);
    char[] data = getPointer().getCharArray(0, length/2);
    return new String(data);
 }

}

but after using it in JNA method call the result is empty (= length is 0 and no data). Do you have please any suggestions how to create correct mapping for BSTR to use it as I/O param of the function? It looks like the BSTR is not passed by reference to the DLL method so result is still empty but it is only my supposition. Maybe the mapping is correct but is wrongly used in method call. Thank in advance for any suggestion.

I can't find a correct "Type for Type" mapping but just to be sure, can you try it this way and get back a string (length > 0).

[ Edit : see Technomage Comment]
ATTENTION : You should be much much more careful when using Memory objects. They get free'd at the native level when the java object gets garbadge collected. This means that your code super(new Memory(value.length()*2+6).share(4)); is just a waste of time because your new Memory(..) disappear the very moment after you pass the line since the .share(4) give a new independant Pointer

class BSTRUtils {
  private BSTR() { }
  public static Memory toNative(String value) {
    Memory m = new Memory(value.length()*2+6);  
    m.setInt(0, value.length()*2);
    m.setString(4, value, true);
    return m;
  }
  public static String toString(PointerByReference pbr) {
    return toString(pbr.getValue());
  }
  public static String toString(Pointer p) {
    int length = p.getInt(0);
    char[] data = p.getCharArray(4, length/2);
    return new String(data);
  }
}

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