Skip to main content

mono_rt/types/
class_field.rs

1use std::ffi::CStr;
2
3use super::{MonoType, MonoVTable, mono_handle};
4use crate::{Result, api};
5
6mono_handle!(MonoClassField);
7
8impl MonoClassField {
9    /// Returns the byte offset of this field within its declaring class.
10    ///
11    /// # Errors
12    ///
13    /// Returns [`crate::MonoError::Uninitialized`] if the Mono API has not been initialized.
14    pub fn offset(self) -> Result<u32> {
15        Ok(api()?.field_get_offset(self.as_ptr()))
16    }
17
18    /// Returns the name of this field as reported by the Mono runtime.
19    ///
20    /// The returned string is copied out of Mono's metadata and is safe to use beyond the
21    /// lifetime of the runtime handle.
22    ///
23    /// # Errors
24    ///
25    /// Returns [`crate::MonoError::Uninitialized`] if the Mono API has not been initialized.
26    pub fn name(self) -> Result<String> {
27        let ptr = api()?.field_get_name(self.as_ptr());
28        if ptr.is_null() {
29            return Ok(String::new());
30        }
31        Ok(unsafe { CStr::from_ptr(ptr) }
32            .to_string_lossy()
33            .into_owned())
34    }
35
36    /// Returns the [`MonoType`] descriptor for this field.
37    ///
38    /// # Errors
39    ///
40    /// Returns [`crate::MonoError::Uninitialized`] if the Mono API has not been initialized.
41    pub fn mono_type(self) -> Result<Option<MonoType>> {
42        let ptr = api()?.field_get_type(self.as_ptr());
43        Ok(MonoType::from_ptr(ptr))
44    }
45
46    /// Reads the static field value into the `out` buffer via the given vtable.
47    ///
48    /// # Errors
49    ///
50    /// Returns [`crate::MonoError::Uninitialized`] if the Mono API has not been initialized.
51    ///
52    /// # Safety
53    ///
54    /// `out` must point to valid memory sized for the field type.
55    pub unsafe fn static_value(self, vtable: MonoVTable, out: *mut c_void) -> Result<()> {
56        api()?.field_static_get_value(vtable.as_ptr(), self.as_ptr(), out);
57        Ok(())
58    }
59}