登录
首页 >  Golang >  Go问答

使用 cgo/JNA 将 Go 中的Java字符串数组传递给Java

来源:stackoverflow

时间:2024-03-12 16:54:26 104浏览 收藏

知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个Golang开发实战,手把手教大家学习《使用 cgo/JNA 将 Go 中的Java字符串数组传递给Java》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!

问题内容

我想通过 jna 将 java 中的 string[] 传递给我的 go 函数。

我的 go 函数具有以下签名:

func predicateeval(keys, values []string, expression string) *c.char

我已经编译了go库,链接模式为“c-shared”。我在 java 中有一个 gostring 定义为:

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;
/**
 * native declaration : coverage_server/predicate_jvm_bridge/lib/libtest.h
* this file was autogenerated by jnaerator,
* a tool written by olivier chafik that uses a few opensource projects..
* for help, please visit nativelibs4java , rococoa, or jna. */ public class _gostring_ extends structure { /** c type : const char* */ public pointer p; public nativesize n; public _gostring_() { super(); } protected list 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 切片定义为:

package predicates;
import com.sun.jna.pointer;
import com.sun.jna.structure;
import java.util.arrays;
import java.util.list;
/**
 * native declaration : coverage_server/predicate_jvm_bridge/lib/libtest.h
* this file was autogenerated by jnaerator,
* a tool written by olivier chafik that uses a few opensource projects..
* for help, please visit nativelibs4java , rococoa, or jna. */ 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 getfieldorder() { return arrays.aslist("data", "len", "cap"); } /** * @param data c type : void*
* @param len c type : goint
* @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 []string 转换为 go string[] 的尝试。

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 端的切片元素时,我遇到了段错误:

unexpected fault address 0xb01dfacedebac1e
fatal error: fault
[signal SIGSEGV: segmentation violation code=0x1 addr=0xb01dfacedebac1e pc=0x10d7d3d6f]

goroutine 17 [running, locked to thread]:

正确答案


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

您的 _gostring_ 映射仅包括指针(4 或 8 字节)和 nativesize(4 或 8 字节 size_t)的分配。此映射假设 pointer 保持有效:

public class _gostring_ extends structure {
    /** c type : const char* */
    public pointer p;
    public nativesize n;
    // constructors, etc.
}

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

  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);
    }
  }

作为直接字节缓冲区,内存位置和(取消)分配机制与普通对象和 gc 不同,但基本原理是一旦你失去了对 java 对象(bytebuffer)的引用,你就无法控制当本机内存将被释放时。 (当 bb 被 gc 时,其内部字段包含在处理时将触发释放的引用。)

一种可能的解决方案是向 _gostring_ 类添加 private 字段,该字段维护对 bytebuffer 的强引用并防止系统回收其内存(可能添加 bytebuffer 构造函数)。

另一个解决方案是使用 jna 的 memory 类作为字符串,并直接将该 memory 对象(扩展 pointer)存储到 p 字段。我不确定您为什么为此应用程序选择直接字节缓冲区,因此这可能不适用于您的用例,但它肯定会简化您的代码。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>