新建一个简单的cmake管理的c++工程,只包含一个MakeLists.txt和src1.cpp,内容分别如下
1cmake_minimum_required(VERSION 3.0) 2 3project(jna_test C CXX) 4 5add_library(foo SHARED src1.cpp) 6 7/* 8 * src1.cpp 9 * 10 * Created on: Jan 28, 2019 11 * Author: link 12 */ 13 14#include <stdio.h> 15#include <string.h> 16#include <iostream> 17#include <stdlib.h> 18 19using namespace std; 20 21class T { 22public: 23 void print() { cout << "T print" << endl;} 24}; 25 26#ifdef __cplusplus 27extern "C" { 28#endif 29 30void foo(char ** output, char * len) { 31 T t; 32 t.print(); 33 *len = 10; 34 *output = (char *) calloc(1, *len); 35 memcpy(*output, "1234567890", *len); 36} 37#ifdef __cplusplus 38} 39#endif
因为JNA只支持C风格动态库接口,而工程是c++风格,必须使用__cplusplus宏和extern "C"把foo函数以C风格输出。foo函数内调用类T.print函数,给*output指针分配10个字节,并复制字符串。
在Java端的测试工程中加入jna依赖坐标
1<dependency> 2 <groupId>net.java.dev.jna</groupId> 3 <artifactId>jna</artifactId> 4 <version>5.2.0</version> 5</dependency>
DirectMap方式调用foo函数
1import com.sun.jna.*; 2import com.sun.jna.ptr.*; 3 4public class DirectJNA { 5 static { 6 //foo是库的名称,且能在系统环境变量LD_LIBRARY_PATH或者JVM参数jna.library.path中能搜索到libfoo.so 7 Native.register("foo"); 8 } 9 10 //映射libfoo.so中的函数foo(char **output, int * len) 11 public static native void foo(PointerByReference bufp, IntByReference lenp); 12 13 14 public static void main(String[] args) { 15 PointerByReference bufp = new PointerByReference(); 16 IntByReference lenp = new IntByReference(); 17 foo(bufp, lenp); 18 Pointer p = bufp.getValue(); 19 byte[] buffer = p.getByteArray(0, lenp.getValue()); 20 System.out.println(new String(buffer)); 21 } 22}
由于是在c库的foo函数分配内存,为了传递给JNA调用,foo函数中并没有释放此内存,JNA对于什么时候释放并没有做交代。
参考
https://github.com/java-native-access/jna/blob/master/www/ByRefArguments.md
https://github.com/java-native-access/jna/blob/master/www/DirectMapping.md