feat(jni): implement JNI object registry and string memory management
This commit is contained in:
parent
3923f7aa28
commit
1a9d0b0153
3 changed files with 77 additions and 0 deletions
|
|
@ -1,4 +1,5 @@
|
|||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
pub mod env;
|
||||
pub mod objects;
|
||||
pub mod types;
|
||||
pub mod vm;
|
||||
|
|
|
|||
64
crates/molotov-core/src/jni/objects.rs
Normal file
64
crates/molotov-core/src/jni/objects.rs
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#![allow(dead_code)]
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::{CStr, CString};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum JniObject {
|
||||
Class(String),
|
||||
String(String, CString),
|
||||
Instance { class_name: String },
|
||||
}
|
||||
|
||||
pub struct JniObjectRegistry {
|
||||
objects: HashMap<usize, JniObject>,
|
||||
next_handle: usize,
|
||||
}
|
||||
|
||||
impl Default for JniObjectRegistry {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl JniObjectRegistry {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
objects: HashMap::new(),
|
||||
next_handle: 1000,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn alloc_class(&mut self, class_name: &str) -> usize {
|
||||
let handle = self.next_handle;
|
||||
self.next_handle += 1;
|
||||
self.objects.insert(handle, JniObject::Class(class_name.to_string()));
|
||||
handle
|
||||
}
|
||||
|
||||
pub fn alloc_string(&mut self, text: &str) -> usize {
|
||||
let handle = self.next_handle;
|
||||
self.next_handle += 1;
|
||||
let c_str = CString::new(text).unwrap_or_default();
|
||||
self.objects.insert(handle, JniObject::String(text.to_string(), c_str));
|
||||
handle
|
||||
}
|
||||
|
||||
pub fn get_string(&self, handle: usize) -> Option<&str> {
|
||||
match self.objects.get(&handle) {
|
||||
Some(JniObject::String(text, _)) => Some(text.as_str()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_string_c_str(&self, handle: usize) -> Option<&CStr> {
|
||||
match self.objects.get(&handle) {
|
||||
Some(JniObject::String(_, c_str)) => Some(c_str.as_c_str()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn release_object(&mut self, handle: usize) -> bool {
|
||||
self.objects.remove(&handle).is_some()
|
||||
}
|
||||
}
|
||||
12
crates/molotov-core/tests/jni_objects_test.rs
Normal file
12
crates/molotov-core/tests/jni_objects_test.rs
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
use molotov_core::jni::objects::JniObjectRegistry;
|
||||
|
||||
#[test]
|
||||
fn test_jni_string_allocation_and_read() {
|
||||
let mut registry = JniObjectRegistry::new();
|
||||
let str_handle = registry.alloc_string("hello_roblox");
|
||||
|
||||
assert_eq!(registry.get_string(str_handle), Some("hello_roblox"));
|
||||
registry.release_object(str_handle);
|
||||
assert_eq!(registry.get_string(str_handle), None);
|
||||
}
|
||||
Reference in a new issue