admin管理员组

文章数量:1278881

I want to test using JDK22+ accessing Rust code through Java FFM. Then I searched online like [1][2] and experimented some testing code. I can successfully access a simple Rust function through Java FFM APIs. For instance,

// Rust
#[no_mangle]
pub extern "C" fn add_numbers(x: i32, y: i32) -> i32 {
    x + y
}


// Jvm
MethodHandle addNumbers = {
  Linker linker = Linker.nativeLinker();
  SymbolLookup rustlib = SymbolLookup.libraryLookup(
    "target/release/libmylib.so",
    Arena.global()
  );
  return linker.downcallHandle(
    rustlib.find("add_numbers").orElseThrow(),
    FunctionDescriptor.of(
      ValueLayout.JAVA_INT,
      ValueLayout.JAVA_INT,
      ValueLayout.JAVA_INT
    )
  );
}  

Object result = addNumbers.invokeExact(10, 20)
System.out.println("Result:" + result)

However, I have a problem that I need to access a complicated Rust struct hashmap, which is an alias to Rust std hashmap, where it in turns references to hashbrown hashmap, where it contains a hash builder and raw table, and so on. I attempted with the code as below, and a question.

  • How to describe a generic field like hashbrown RawTable's alloc and a field that contains generic type parameter e.g. PhantomData through Java FFM APIs?

Many thanks

// Code attempted 
StructLayout nonNull = MemoryLayout.structLayout(
  ValueLayout.ADDRESS
    .withTargetLayout(
      MemoryLayout.sequenceLayout(0, ValueLayout.JAVA_BYTE)
    )
    .withName("pointer")
);
StructLayout rawTableInner = MemoryLayout.structLayout(
  ValueLayout.JAVA_INT.withName("bucket_mask"),
  nonNull.withName("ctrl"),
  ValueLayout.JAVA_INT.withName("growth_left"),
  ValueLayout.JAVA_INT.withName("items")
);
StructLayout rawTable = MemoryLayout.structLayout(
  rawTableInner.withName("table"),
  ???, // how to describe alloc which is a generic type A here?
  ???  // how to describe PhantomData<T> here?
) 

Edit Remove other questions and focus on one question. Thanks.

[1]. Java FFM, how to link a java object with a C struct?

[2]. .html

本文标签: