如何在Java/Rust服务之间通过JNI使用原始指针重用对象

huangapple go评论91阅读模式
英文:

how to reuse objects between a java/rust service via JNI using raw pointer

问题

在每次从 Java 服务到 Rust 服务的调用中,我打算通过 JNI 传递单例(指针),然后在 Rust 中使用原始指针获取对象的引用并执行业务逻辑。

指针是否保证始终指向正确的对象?还是我需要将其固定,以确保它不会移动?

英文:

I've the following scenario. I've a java service that talks to a rust service via JNI.

I'm planning to re-use an object across multiple jni calls. So, I'm planning to create it in the first JNI call on the heap using a Box and return a raw pointer to the same. I intent to store it as a singleton in the java service.

In each call from java service to rust service , I intent to pass along the singleton(pointer) via JNI, and get a reference to the object using the raw pointer in rust and perform business logic.

Is it guranteed that the pointer will always point to the correct object? or do I need to pin it so that it doesn't move?

答案1

得分: 1

你不需要将它固定。

Pin 不是语言保证;它是一个库的保证。它阻止Rust代码移动该值。如果你不在Rust中移动该值,它将不会被移动。它将静默地保持在原地,你可以放心依赖于它。

英文:

You do not need to pin it.

Pin is not a language guarantee; it is a library guarantee. It prevents Rust code from moving the value. If you will not move the value in Rust, it will not be moved. It will stay where it is silently and you can definitely rely on that.

答案2

得分: 1

由于您费了很大的劲将您的装箱对象的地址伪装成一个简单的数字,JVM 不会对其做任何特殊处理。
由您来确保该地址保持有效,这在这种情况下主要意味着不要让 Box 被丢弃。根据我所了解的 Rust,这意味着要么调用 Box::into_raw 要么调用 Box::leak

英文:

Since you took great pains in disguising the address of your boxed object as a simple number, the JVM will not do anything special with that.
It is up to you to ensure that that address remains valid, which in this case mostly means not letting the Box be dropped. From what little I know of Rust, that means either calling Box::into_raw or Box::leak.

huangapple
  • 本文由 发表于 2023年7月6日 16:07:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76626752.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定