首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过cgo/JNA传递Java字符串数组[]字符串

如何通过cgo/JNA传递Java字符串数组[]字符串
EN

Stack Overflow用户
提问于 2021-07-21 07:23:09
回答 1查看 266关注 0票数 3

我想通过JNA在Java中传递一个String[]到Go函数。

我的go函数有以下签名:

代码语言:javascript
复制
func PredicateEval(keys, values []string, expression string) *C.char

我已经编译了连接模式为“c共享”的go库。我在java中有一个GoString,定义为:

代码语言:javascript
复制
package predicates;
import com.ochafik.lang.jnaerator.runtime.NativeSize;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import java.util.Arrays;
import java.util.List;
/**
 * <i>native declaration : coverage_server/predicate_jvm_bridge/lib/libtest.h</i><br>
 * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br>
 * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br>
 * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>.
 */
public class _GoString_ extends Structure {
    /** C type : const char* */
    public Pointer p;
    public NativeSize n;
    public _GoString_() {
        super();
    }
    protected List<String> getFieldOrder() {
        return Arrays.asList("p", "n");
    }
    /** @param p C type : const char* */
    public _GoString_(Pointer p, NativeSize n) {
        super();
        this.p = p;
        this.n = n;
    }
    public static class ByReference extends _GoString_ implements Structure.ByReference {
        
    };
    public static class ByValue extends _GoString_ implements Structure.ByValue {
        
    };
}

我还将Go片定义为:

代码语言:javascript
复制
package predicates;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import java.util.Arrays;
import java.util.List;
/**
 * <i>native declaration : coverage_server/predicate_jvm_bridge/lib/libtest.h</i><br>
 * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br>
 * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br>
 * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>.
 */
public class GoSlice extends Structure {
    /** C type : void* */
    public Pointer data;
    /** C type : GoInt */
    public long len;
    /** C type : GoInt */
    public long cap;
    public GoSlice() {
        super();
    }
    protected List<String> getFieldOrder() {
        return Arrays.asList("data", "len", "cap");
    }
    /**
     * @param data C type : void*<br>
     * @param len C type : GoInt<br>
     * @param cap C type : GoInt
     */
    public GoSlice(Pointer data, long len, long cap) {
        super();
        this.data = data;
        this.len = len;
        this.cap = cap;
    }
    public static class ByReference extends GoSlice implements Structure.ByReference {
        
    };
    public static class ByValue extends GoSlice implements Structure.ByValue {
        
    };
}

这是我将Java []字符串转换为Go string[]的尝试。

代码语言:javascript
复制
  static {
    try {
      Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
      field.setAccessible(true);
      unsafe = (sun.misc.Unsafe) field.get(null);
      Class<?> clazz = ByteBuffer.allocateDirect(0).getClass();
      DIRECT_BYTE_BUFFER_ADDRESS_OFFSET = unsafe.objectFieldOffset(Buffer.class.getDeclaredField("address"));
      DIRECT_BYTE_BUFFER_CLASS = clazz;
    } catch (Exception e) {
      throw new AssertionError(e);
    }
  }

  private static long getAddress(ByteBuffer buffer) {
    assert buffer.getClass() == DIRECT_BYTE_BUFFER_CLASS;
    return unsafe.getLong(buffer, DIRECT_BYTE_BUFFER_ADDRESS_OFFSET);
  }

  public static _GoString_.ByValue JavaStringToGo(String jstr) {
    try {
      byte[] bytes = jstr.getBytes("utf-8");
      //ByteBuffer bb = ByteBuffer.wrap(bytes);
      ByteBuffer bb = ByteBuffer.allocateDirect(bytes.length);
      bb.put(bytes);
      Pointer p = new Pointer(getAddress(bb));
      _GoString_.ByValue value = new _GoString_.ByValue();

      value.n = new NativeSize(bytes.length);
      value.p = p;
      return value;
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e);
    }
  }
  
  public static GoSlice.ByValue JavaStringArrayToGoStringSlice(String[] strings) {
    _GoString_.ByValue[] goStrings = new _GoString_.ByValue[strings.length];
    for (int i = 0; i < strings.length; i++) {
      goStrings[i] = JavaStringToGo(strings[i]);
    }

    Memory arr = new Memory(strings.length * Native.getNativeSize(_GoString_.class));
    for (int i = 0; i < strings.length; i++) {
      System.out.println(Native.getNativeSize(_GoString_.class));
      byte[] bytes = goStrings[0].getPointer().getByteArray(0, Native.getNativeSize(_GoString_.class));
      arr.write(i*Native.getNativeSize(_GoString_.class), bytes, 0, bytes.length);
    }
    GoSlice.ByValue slice = new GoSlice.ByValue();
    slice.data = arr;
    slice.len = strings.length;
    slice.cap = strings.length;

    return slice;
  }

所有内容都会编译,但是当我尝试访问Go侧的片元素时,我会得到一个seg错误:

代码语言:javascript
复制
unexpected fault address 0xb01dfacedebac1e
fatal error: fault
[signal SIGSEGV: segmentation violation code=0x1 addr=0xb01dfacedebac1e pc=0x10d7d3d6f]

goroutine 17 [running, locked to thread]:
EN

回答 1

Stack Overflow用户

发布于 2021-07-21 19:06:43

您正在失去对实际字符串的内存分配的跟踪(和控制)。

_GoString_的映射只包括分配指针(4或8字节)和NativeSize (4或8字节size_t)。此映射假定Pointer仍然有效:

代码语言:javascript
复制
public class _GoString_ extends Structure {
    /** C type : const char* */
    public Pointer p;
    public NativeSize n;
    // constructors, etc.
}

但是,当您将值分配给p时,您只需要跟踪指针的地址,而不是实际的内存分配(我已经在代码中添加了注释):

代码语言:javascript
复制
  public static _GoString_.ByValue JavaStringToGo(String jstr) {
    try {
      byte[] bytes = jstr.getBytes("utf-8");
      // 
      // Here you allocate memory for the bytes
      //
      ByteBuffer bb = ByteBuffer.allocateDirect(bytes.length);
      bb.put(bytes);
      // 
      // Here you only keep track of the pointer to the bytes
      //
      Pointer p = new Pointer(getAddress(bb));
      // 
      // You never reference bb again, it is no longer reachable
      // and its allocation can be reclaimed by the system
      //
      _GoString_.ByValue value = new _GoString_.ByValue();

      value.n = new NativeSize(bytes.length);
      value.p = p;
      return value;
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e);
    }
  }

作为直接字节缓冲区,内存位置和(De)分配机制与普通对象和GC不同,但基本原则是,一旦丢失了对Java ( ByteBuffer)的引用,您就无法控制何时释放该本机内存。(当bb是GC的时候,它的内部字段包括将在处理它时触发去分配的引用。)

一种可能的解决方案是向您的private类中添加一个_GoString_字段,该字段维护对ByteBuffer的强大引用,并阻止系统恢复其内存(可能会添加ByteBuffer构造器)。

另一种解决方案是对String使用JNA的Memory类,并直接将Memory对象(扩展Pointer)存储到p字段。我不知道为什么您选择了这个应用程序的直接字节缓冲区,所以这可能不适用于您的用例,但它肯定会简化您的代码。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68465480

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档