Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Storing struct as a field #77

Open
fdorothy opened this issue Nov 7, 2024 · 2 comments
Open

Storing struct as a field #77

fdorothy opened this issue Nov 7, 2024 · 2 comments

Comments

@fdorothy
Copy link

fdorothy commented Nov 7, 2024

I'm pretty new to Rust and JNI, so sorry if this is a bad question.

Is there a way to store a raw pointer to a struct as a field?

For example, I have a complex structure named Runtime. This has properties that won't serialize to Java, but that's fine, I just want a reference to it and use its functions on the Rust side. I was thinking I could add runtime as a field using JObject:

    #[derive(Signature, TryIntoJavaValue, IntoJavaValue, TryFromJavaValue)]
    #[package()]
    pub struct JniRunner<'env: 'borrow, 'borrow> {
        #[instance]
        raw: AutoLocal<'env, 'borrow>,
        #[field]
        runtime: Field<'env, 'borrow, JObject<'env>>,
    }

However, I'm not clear on how to convert my Runtime struct into a JObject using this package's version of JNI. I was thinking I could do something like below, but JNI 0.19.0 doesn't have the from_raw method on JObject:

let raw_ptr = Box::into_raw(Box::new(Runtime {}));
self.runtime.set(unsafe { JObject::from_raw(raw_ptr as jobject) });

Is there a better way to store a raw pointer to a complex struct in robusta?

@giovanniberti
Copy link
Owner

giovanniberti commented Nov 7, 2024

Hi!
I don't think there is a much better way right now (regarding your question about jni 0.19: you could cast the raw pointer to *mut Runtime and then to *mut _jobject and use that with JObject::from).

If Runtime implemented IntoJavaValue or similar you could use its conversion methods, but if it doesn't then I think yours is the only way.

@fdorothy
Copy link
Author

Hello and thanks!

I've gotten a bit further along thanks to your help. I am now running into an issue where the JObject doesn't appear to be getting set by self.runtime.set(jobj) (which is a field). My code:

#[field]
runtime: Field<'env, 'borrow, JObject<'env>>,

...

let raw_ptr = Box::into_raw(Box::new(runtime));
let jobj = JObject::from(raw_ptr as jobject);
println!("{:#?}", jobj);
self.runtime.set(jobj)?;
println!("{:#?}", self.runtime.get()?);

This outputs the following:

JObject {
    internal: 0x0000600002668700,
    lifetime: PhantomData<&()>,
}
JObject {
    internal: 0x0000000000000000,
    lifetime: PhantomData<&()>,
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants