此文档陆续记录JNA的使用经验!
会根据实际操作陆续更新
- 带有返回值的字符串形参
-
int lib_ver(unsinged char *buff); 功 能:读取软件版本号 参 数:buff:存放版本号的缓冲区,长度18字节(包括结束字符’\0’)。 返 回:成功则返回 0 例:unsigned char buff[18]; lib_ver(buff); printf(“software version is %s”,buff);
- JNA JAVA对应方法: int lib_ver(byte[] buf);
- Java调用方式:
public synchronized String version() throws RuntimeException { byte[] buf = new byte[18]; machine.lib_ver(buf); return Native.toString(buf); }
- 参考资料:官方解答How to return a out String paramter in the JNA?
How do I read back a function's string result? Suppose you have a function: // Returns the number of characters written to the buffer int getString(char* buffer, int bufsize); The native code is expecting a fixed-size buffer, which it will fill in with the requested data. A Java String is not appropriate here, since Strings are immutable. Nor is a Java StringBuffer, since the native code only fills the buffer and does not change its size. The appropriate argument type would be either byte[], Memory, or an NIO Buffer, with the size of the object passed as the second argument. The method Native.toString(byte[]) may then be used to convert the array of byte into a Java String.
- 字符串转换指定编码,解决乱码问题:Native.toString(buf, "GBK")
-