unity/il2cpp/
method.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
use std::ffi::CStr;

use super::{class::Il2CppClass, Il2CppType};

/// A type alias for `Option<&MethodInfo>`. Useful when hooking Il2Cpp methods.
pub type OptionalMethod = Option<&'static MethodInfo>;

/// Type representing the reflection information of a C# method.
/// 
/// Can be used to query various things such as the name, argument count and much more.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct MethodInfo {
    pub method_ptr: *mut u8,
    pub invoker_method: *const u8,
    pub name: *const u8,
    pub class: Option<&'static Il2CppClass>,
    pub return_type: *const u8,
    pub parameters: *const ParameterInfo,
    pub info_or_definition: *const u8,
    pub generic_method_or_container: *const u8,
    pub token: u32,
    pub flags: u16,
    pub iflags: u16,
    pub slot: u16,
    pub parameters_count: u8,
    pub bitflags: u8,
}

unsafe impl Send for MethodInfo {}
unsafe impl Sync for MethodInfo {}

#[repr(C)]
#[derive(Clone, Copy)]
pub struct ParameterInfo {
    pub name: *const u8,
    pub position: i32,
    pub token: u32,
    pub parameter_type: &'static Il2CppType,
}

impl MethodInfo {
    pub fn new() -> Self {
        Self {
            method_ptr: 0 as _,
            invoker_method: 0 as _,
            name: 0 as _,
            class: None,
            return_type: 0 as _,
            parameters: 0 as _,
            info_or_definition: 0 as _,
            generic_method_or_container: 0 as _,
            bitflags: 0,
            flags: 0,
            iflags: 0,
            parameters_count: 0,
            slot: 0,
            token: 0,
        }
    }

    pub fn new_from(base: Self) -> Self {
        Self {
            invoker_method: 0 as _,
            bitflags: 0,
            flags: 0,
            iflags: 0,
            slot: 0,
            token: 0,
            ..base
        }
    }
}

impl MethodInfo {
    /// Get the name of the method, if set.
    pub fn get_name(&self) -> Option<String> {
        if self.name.is_null() {
            None
        } else {
            Some(unsafe { String::from_utf8_lossy(CStr::from_ptr(self.name as _).to_bytes()).to_string() })
        }
    }

    /// Get the parameters expected by the method.
    pub fn get_parameters(&self) -> &[ParameterInfo] {
        unsafe { std::slice::from_raw_parts(self.parameters, self.parameters_count as _) }
    }
}

impl ParameterInfo {
    /// Get the name of the parameter, if set.
    pub fn get_name(&self) -> Option<String> {
        if self.name.is_null() {
            None
        } else {
            Some(unsafe { String::from_utf8_lossy(CStr::from_ptr(self.name as _).to_bytes()).to_string() })
        }
    }
}