Created
July 11, 2020 21:10
-
-
Save crossworth/5c4932cecd703a431cea3da33089dcc7 to your computer and use it in GitHub Desktop.
BSTRUtils JNA Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.sun.jna.Memory; | |
import com.sun.jna.Pointer; | |
import com.sun.jna.ptr.PointerByReference; | |
/** | |
* BSTRUtils faz a conversão do tipo String para BSTR. | |
* Basicamente BSTR é um tipo de string similar a uma string wide comum em C do *Windows*. | |
* Basicamente uma string BSTR tem um prefix inteiro de 4bytes informando o tamanho da string | |
* seguido pela string (cada carácter contendo 2bytes) e para finalizar um null terminator de 2bytes. | |
* <p> | |
* https://docs.microsoft.com/en-us/previous-versions/windows/desktop/automat/bstr | |
* https://stackoverflow.com/questions/4924233/mapping-forbstr-data-type-in-jna | |
*/ | |
public class BSTRUtils { | |
private BSTRUtils() { | |
} | |
public static Memory toNative(String value) { | |
Memory m = new Memory(value.length() * 2 + 6); // 4bytes do inteiro + 2 bytes do null terminator | |
m.setInt(0, value.length() * 2); // define-se o tamanho da string (calculado * 2 para tornar ela wide) | |
m.setWideString(4, value); // define-se a string como wide no offset 4 (para não sobre escrever o tamanho) | |
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment