Skip to main content

hao_runtime/
mono.rs

1//! Hosting Mono through its embedding API.
2
3use std::{
4    collections::HashMap,
5    ffi::{c_char, c_int, c_void, CString},
6    path::{Path, PathBuf},
7    sync::{Mutex, OnceLock},
8};
9
10use libloading::Library;
11
12use crate::error::{Error, Result};
13
14type Ptr = *mut c_void;
15
16/// Where to find Mono.
17#[derive(Debug, Clone, Default)]
18#[cfg_attr(feature = "reflect", derive(facet::Facet))]
19pub struct MonoOptions {
20    /// Path to the Mono shared library (`libmonosgen-2.0.so`, `mono-2.0-bdwgc.dll`, ...).
21    /// Defaults to the system Mono.
22    pub library: Option<PathBuf>,
23    /// The directory holding the `mono/4.5` class libraries, e.g. `/usr/lib` or a
24    /// Unity game's `MonoBleedingEdge/lib`. Defaults to Mono's built in path.
25    pub assemblies_dir: Option<PathBuf>,
26    /// Mono's config directory, e.g. `/etc`. Defaults to Mono's built in path.
27    pub config_dir: Option<PathBuf>,
28}
29
30struct Api {
31    set_dirs: unsafe extern "C" fn(*const c_char, *const c_char),
32    jit_init_version: unsafe extern "C" fn(*const c_char, *const c_char) -> Ptr,
33    thread_attach: unsafe extern "C" fn(Ptr) -> Ptr,
34    domain_assembly_open: unsafe extern "C" fn(Ptr, *const c_char) -> Ptr,
35    image_open_from_data_with_name:
36        unsafe extern "C" fn(*const c_char, u32, c_int, *mut c_int, c_int, *const c_char) -> Ptr,
37    assembly_load_from_full: unsafe extern "C" fn(Ptr, *const c_char, *mut c_int, c_int) -> Ptr,
38    assembly_get_image: unsafe extern "C" fn(Ptr) -> Ptr,
39    class_from_name: unsafe extern "C" fn(Ptr, *const c_char, *const c_char) -> Ptr,
40    class_get_method_from_name: unsafe extern "C" fn(Ptr, *const c_char, c_int) -> Ptr,
41    method_get_unmanaged_thunk: unsafe extern "C" fn(Ptr) -> Ptr,
42    compile_method: unsafe extern "C" fn(Ptr) -> Ptr,
43    get_root_domain: unsafe extern "C" fn() -> Ptr,
44    // Bound for completeness; the `enumerate` path resolves virtual methods on
45    // the object directly via `object_get_virtual_method`, which needs no
46    // separate class lookup.
47    #[allow(dead_code)]
48    object_get_class: unsafe extern "C" fn(Ptr) -> Ptr,
49    object_get_virtual_method: unsafe extern "C" fn(Ptr, Ptr) -> Ptr,
50    runtime_invoke: unsafe extern "C" fn(Ptr, Ptr, *mut Ptr, *mut Ptr) -> Ptr,
51    object_unbox: unsafe extern "C" fn(Ptr) -> Ptr,
52    class_get_methods: unsafe extern "C" fn(Ptr, *mut Ptr) -> Ptr,
53    method_get_name: unsafe extern "C" fn(Ptr) -> *const c_char,
54    class_get_name: unsafe extern "C" fn(Ptr) -> *const c_char,
55    class_get_namespace: unsafe extern "C" fn(Ptr) -> *const c_char,
56    image_get_table_rows: unsafe extern "C" fn(Ptr, c_int) -> c_int,
57    class_get: unsafe extern "C" fn(Ptr, u32) -> Ptr,
58    get_corlib: unsafe extern "C" fn() -> Ptr,
59}
60
61/// The `MONO_TABLE_TYPEDEF` index for `mono_image_get_table_rows`.
62const MONO_TABLE_TYPEDEF: c_int = 2;
63/// The top byte of a `TypeDef` metadata token.
64const MONO_TOKEN_TYPE_DEF: u32 = 0x0200_0000;
65
66/// The three corlib `MonoMethod*` (as `usize`) the `enumerate` walk needs,
67/// resolved once so each call avoids a corlib lookup.
68struct EnumMethods {
69    get_enumerator: usize,
70    move_next: usize,
71    get_current: usize,
72}
73
74pub(crate) struct Mono {
75    _library: Library,
76    api: Api,
77    domain: Ptr,
78    images: Mutex<HashMap<String, usize>>,
79    enum_methods: OnceLock<EnumMethods>,
80}
81
82// Mono is thread safe once threads are attached, which every call does.
83unsafe impl Send for Mono {}
84unsafe impl Sync for Mono {}
85
86fn default_library() -> Option<PathBuf> {
87    let names: &[&str] = if cfg!(windows) {
88        &["mono-2.0-sgen.dll", "mono-2.0-bdwgc.dll"]
89    } else if cfg!(target_os = "macos") {
90        &["libmonosgen-2.0.dylib"]
91    } else {
92        &["libmonosgen-2.0.so", "libmonosgen-2.0.so.1"]
93    };
94    let dirs = [
95        "/usr/lib",
96        "/usr/local/lib",
97        "/usr/lib/x86_64-linux-gnu",
98        "/Library/Frameworks/Mono.framework/Versions/Current/lib",
99        r"C:\Program Files\Mono\bin",
100    ];
101    dirs.iter()
102        .flat_map(|d| names.iter().map(move |n| Path::new(d).join(n)))
103        .find(|p| p.exists())
104}
105
106fn cstring(value: &str) -> Result<CString> {
107    CString::new(value).map_err(|_| Error::Other(format!("{:?} contains a nul byte", value)))
108}
109
110/// Copies a Mono-owned C string into an owned `String`. The memory belongs to
111/// Mono (interned class/method names), so it is read but never freed. A null
112/// pointer, or one holding invalid UTF-8, yields an empty string.
113fn cstr(ptr: *const c_char) -> String {
114    if ptr.is_null() {
115        return String::new();
116    }
117    unsafe { std::ffi::CStr::from_ptr(ptr) }
118        .to_string_lossy()
119        .into_owned()
120}
121
122impl Mono {
123    /// Opens the Mono library and resolves its symbols, without initialising it.
124    /// On `attach` the library is already loaded, so this hands back the same one.
125    fn open(options: &MonoOptions) -> Result<(Library, Api)> {
126        let path = options
127            .library
128            .clone()
129            .or_else(default_library)
130            .ok_or_else(|| Error::NotFound("the Mono runtime library".into()))?;
131        let library = unsafe { Library::new(&path) }
132            .map_err(|e| Error::Library(path.display().to_string(), e))?;
133
134        macro_rules! symbol {
135            ($name:literal) => {
136                *unsafe { library.get(concat!($name, "\0").as_bytes()) }
137                    .map_err(|e| Error::Library($name.into(), e))?
138            };
139        }
140        let api = Api {
141            set_dirs: symbol!("mono_set_dirs"),
142            jit_init_version: symbol!("mono_jit_init_version"),
143            thread_attach: symbol!("mono_thread_attach"),
144            domain_assembly_open: symbol!("mono_domain_assembly_open"),
145            image_open_from_data_with_name: symbol!("mono_image_open_from_data_with_name"),
146            assembly_load_from_full: symbol!("mono_assembly_load_from_full"),
147            assembly_get_image: symbol!("mono_assembly_get_image"),
148            class_from_name: symbol!("mono_class_from_name"),
149            class_get_method_from_name: symbol!("mono_class_get_method_from_name"),
150            method_get_unmanaged_thunk: symbol!("mono_method_get_unmanaged_thunk"),
151            compile_method: symbol!("mono_compile_method"),
152            get_root_domain: symbol!("mono_get_root_domain"),
153            object_get_class: symbol!("mono_object_get_class"),
154            object_get_virtual_method: symbol!("mono_object_get_virtual_method"),
155            runtime_invoke: symbol!("mono_runtime_invoke"),
156            object_unbox: symbol!("mono_object_unbox"),
157            class_get_methods: symbol!("mono_class_get_methods"),
158            method_get_name: symbol!("mono_method_get_name"),
159            class_get_name: symbol!("mono_class_get_name"),
160            class_get_namespace: symbol!("mono_class_get_namespace"),
161            image_get_table_rows: symbol!("mono_image_get_table_rows"),
162            class_get: symbol!("mono_class_get"),
163            get_corlib: symbol!("mono_get_corlib"),
164        };
165        Ok((library, api))
166    }
167
168    /// Attaches to a Mono runtime already running in this process, for a mod
169    /// loaded into a Unity Mono game. `options.library` should point at the
170    /// game's own Mono (e.g. `MonoBleedingEdge/.../libmonobdwgc-2.0.so`); loading
171    /// it by name returns the already-loaded instance rather than a fresh copy.
172    pub fn attach(options: &MonoOptions) -> Result<Self> {
173        let (library, api) = Self::open(options)?;
174        let domain = unsafe { (api.get_root_domain)() };
175        if domain.is_null() {
176            return Err(Error::Other(
177                "no Mono runtime is running in this process".into(),
178            ));
179        }
180        unsafe { (api.thread_attach)(domain) };
181        Ok(Self {
182            _library: library,
183            api,
184            domain,
185            images: Mutex::new(HashMap::new()),
186            enum_methods: OnceLock::new(),
187        })
188    }
189
190    pub fn new(options: &MonoOptions) -> Result<Self> {
191        let (library, api) = Self::open(options)?;
192
193        let assemblies = options
194            .assemblies_dir
195            .as_ref()
196            .map(|p| cstring(&p.to_string_lossy()))
197            .transpose()?;
198        let config = options
199            .config_dir
200            .as_ref()
201            .map(|p| cstring(&p.to_string_lossy()))
202            .transpose()?;
203        let domain_name = cstring("hao")?;
204        let version = cstring("v4.0.30319")?;
205        let domain = unsafe {
206            if assemblies.is_some() || config.is_some() {
207                let default_config = cstring("/etc")?;
208                let default_assemblies = cstring("/usr/lib")?;
209                (api.set_dirs)(
210                    assemblies.as_ref().unwrap_or(&default_assemblies).as_ptr(),
211                    config.as_ref().unwrap_or(&default_config).as_ptr(),
212                );
213            }
214            (api.jit_init_version)(domain_name.as_ptr(), version.as_ptr())
215        };
216        if domain.is_null() {
217            return Err(Error::Other("mono_jit_init_version failed".into()));
218        }
219
220        Ok(Self {
221            _library: library,
222            api,
223            domain,
224            images: Mutex::new(HashMap::new()),
225            enum_methods: OnceLock::new(),
226        })
227    }
228
229    /// Attaches the calling thread so it can run managed code.
230    pub fn attach_thread(&self) {
231        unsafe { (self.api.thread_attach)(self.domain) };
232    }
233
234    fn register(&self, name: &str, assembly: Ptr) -> Result<()> {
235        let image = unsafe { (self.api.assembly_get_image)(assembly) };
236        if image.is_null() {
237            return Err(Error::Other(format!("{} has no image", name)));
238        }
239        self.images
240            .lock()
241            .unwrap_or_else(|e| e.into_inner())
242            .insert(name.to_owned(), image as usize);
243        Ok(())
244    }
245
246    pub fn load_assembly(&self, path: &Path) -> Result<()> {
247        self.attach_thread();
248        let name = path
249            .file_stem()
250            .map(|s| s.to_string_lossy().into_owned())
251            .unwrap_or_default();
252        let c_path = cstring(&path.to_string_lossy())?;
253        let assembly = unsafe { (self.api.domain_assembly_open)(self.domain, c_path.as_ptr()) };
254        if assembly.is_null() {
255            return Err(Error::NotFound(path.display().to_string()));
256        }
257        self.register(&name, assembly)
258    }
259
260    pub fn load_assembly_bytes(&self, name: &str, bytes: &[u8]) -> Result<()> {
261        self.attach_thread();
262        let c_name = cstring(name)?;
263        let mut status = 0;
264        unsafe {
265            let image = (self.api.image_open_from_data_with_name)(
266                bytes.as_ptr().cast(),
267                bytes.len() as u32,
268                1,
269                &mut status,
270                0,
271                c_name.as_ptr(),
272            );
273            if image.is_null() {
274                return Err(Error::Other(format!(
275                    "could not open image {} ({})",
276                    name, status
277                )));
278            }
279            let assembly =
280                (self.api.assembly_load_from_full)(image, c_name.as_ptr(), &mut status, 0);
281            if assembly.is_null() {
282                return Err(Error::Other(format!(
283                    "could not load assembly {} ({})",
284                    name, status
285                )));
286            }
287            self.register(name, assembly)
288        }
289    }
290
291    /// The `MonoImage*` of a loaded assembly, from the registration cache.
292    fn image(&self, assembly: &str) -> Result<Ptr> {
293        let image = *self
294            .images
295            .lock()
296            .unwrap_or_else(|e| e.into_inner())
297            .get(assembly)
298            .ok_or_else(|| Error::NotFound(format!("loaded assembly {}", assembly)))?;
299        Ok(image as Ptr)
300    }
301
302    /// Resolves `type_name::method` to a `MonoMethod*`, matching any arity.
303    fn resolve_method(&self, assembly: &str, type_name: &str, method: &str) -> Result<Ptr> {
304        self.resolve_method_arity(assembly, type_name, method, -1)
305    }
306
307    /// Resolves `type_name::method` to a `MonoMethod*`, matching the overload
308    /// with `params` parameters (`-1` matches any arity).
309    fn resolve_method_arity(
310        &self,
311        assembly: &str,
312        type_name: &str,
313        method: &str,
314        params: c_int,
315    ) -> Result<Ptr> {
316        self.attach_thread();
317        let image = self.image(assembly)?;
318        let (namespace, name) = type_name.rsplit_once('.').unwrap_or(("", type_name));
319        let (namespace, name, method_name) =
320            (cstring(namespace)?, cstring(name)?, cstring(method)?);
321        unsafe {
322            let class = (self.api.class_from_name)(image, namespace.as_ptr(), name.as_ptr());
323            if class.is_null() {
324                return Err(Error::NotFound(format!(
325                    "type {} in {}",
326                    type_name, assembly
327                )));
328            }
329            let method_ptr =
330                (self.api.class_get_method_from_name)(class, method_name.as_ptr(), params);
331            if method_ptr.is_null() {
332                return Err(Error::NotFound(format!("method {}::{}", type_name, method)));
333            }
334            Ok(method_ptr)
335        }
336    }
337
338    pub fn function_pointer(
339        &self,
340        assembly: &str,
341        type_name: &str,
342        method: &str,
343    ) -> Result<*const c_void> {
344        let method_ptr = self.resolve_method(assembly, type_name, method)?;
345        let thunk = unsafe { (self.api.method_get_unmanaged_thunk)(method_ptr) };
346        if thunk.is_null() {
347            return Err(Error::Other(format!(
348                "no unmanaged thunk for {}::{}",
349                type_name, method
350            )));
351        }
352        Ok(thunk)
353    }
354
355    /// The method's JIT-compiled native code, callable with the managed calling
356    /// convention and with no trailing exception argument. Mono can do this for
357    /// any static method, so there is no `[UnmanagedCallersOnly]` requirement.
358    pub fn method_pointer(
359        &self,
360        assembly: &str,
361        type_name: &str,
362        method: &str,
363    ) -> Result<*const c_void> {
364        let method_ptr = self.resolve_method(assembly, type_name, method)?;
365        let code = unsafe { (self.api.compile_method)(method_ptr) };
366        if code.is_null() {
367            return Err(Error::Other(format!(
368                "could not compile {}::{}",
369                type_name, method
370            )));
371        }
372        Ok(code)
373    }
374
375    /// Like [`method_pointer`](Self::method_pointer) but selects the overload
376    /// with `param_count` parameters, so it works with overloaded methods.
377    /// `mono_class_get_method_from_name` matches on name and arity natively.
378    pub fn find_method(
379        &self,
380        assembly: &str,
381        type_name: &str,
382        method: &str,
383        param_count: c_int,
384    ) -> Result<*const c_void> {
385        let method_ptr = self.resolve_method_arity(assembly, type_name, method, param_count)?;
386        let code = unsafe { (self.api.compile_method)(method_ptr) };
387        if code.is_null() {
388            return Err(Error::Other(format!(
389                "could not compile {}::{}({} params)",
390                type_name, method, param_count
391            )));
392        }
393        Ok(code)
394    }
395
396    /// Resolves a well-known corlib method to a native-callable pointer, using
397    /// Mono's own corlib image (`mono_get_corlib`) rather than a loaded
398    /// assembly. The type is `namespace.name`, the overload is picked by
399    /// `arity` (`-1` matches any).
400    #[cfg(feature = "hao")]
401    pub fn corlib_method_pointer(
402        &self,
403        namespace: &str,
404        name: &str,
405        method: &str,
406        arity: c_int,
407    ) -> Result<*const c_void> {
408        self.attach_thread();
409        let corlib = unsafe { (self.api.get_corlib)() };
410        if corlib.is_null() {
411            return Err(Error::Other("mono_get_corlib returned null".into()));
412        }
413        let (namespace_c, name_c, method_c) =
414            (cstring(namespace)?, cstring(name)?, cstring(method)?);
415        unsafe {
416            let class = (self.api.class_from_name)(corlib, namespace_c.as_ptr(), name_c.as_ptr());
417            if class.is_null() {
418                return Err(Error::NotFound(format!(
419                    "corlib type {}.{}",
420                    namespace, name
421                )));
422            }
423            let method_ptr = (self.api.class_get_method_from_name)(class, method_c.as_ptr(), arity);
424            if method_ptr.is_null() {
425                return Err(Error::NotFound(format!(
426                    "corlib method {}.{}::{}",
427                    namespace, name, method
428                )));
429            }
430            let code = (self.api.compile_method)(method_ptr);
431            if code.is_null() {
432                return Err(Error::Other(format!(
433                    "could not compile corlib {}::{}",
434                    name, method
435                )));
436            }
437            Ok(code)
438        }
439    }
440
441    /// Returns the full names (`namespace.name`, or bare `name` when the type
442    /// has no namespace) of every type in a loaded assembly, by walking the
443    /// `TypeDef` metadata table.
444    pub fn type_names(&self, assembly: &str) -> Result<Vec<String>> {
445        self.attach_thread();
446        let image = self.image(assembly)?;
447        let rows = unsafe { (self.api.image_get_table_rows)(image, MONO_TABLE_TYPEDEF) };
448        let mut out = Vec::new();
449        // Row 1 is the compiler-synthesised `<Module>` type; real types start at 2.
450        for row in 2..=rows.max(0) as u32 {
451            let class = unsafe { (self.api.class_get)(image, MONO_TOKEN_TYPE_DEF | row) };
452            if class.is_null() {
453                continue;
454            }
455            let namespace = cstr(unsafe { (self.api.class_get_namespace)(class) });
456            let name = cstr(unsafe { (self.api.class_get_name)(class) });
457            out.push(if namespace.is_empty() {
458                name
459            } else {
460                format!("{}.{}", namespace, name)
461            });
462        }
463        Ok(out)
464    }
465
466    /// Returns the names of every method declared on a type in a loaded
467    /// assembly, by iterating the class with `mono_class_get_methods`.
468    pub fn method_names(&self, assembly: &str, type_name: &str) -> Result<Vec<String>> {
469        self.attach_thread();
470        let image = self.image(assembly)?;
471        let (namespace, name) = type_name.rsplit_once('.').unwrap_or(("", type_name));
472        let (namespace_c, name_c) = (cstring(namespace)?, cstring(name)?);
473        let class =
474            unsafe { (self.api.class_from_name)(image, namespace_c.as_ptr(), name_c.as_ptr()) };
475        if class.is_null() {
476            return Err(Error::NotFound(format!(
477                "type {} in {}",
478                type_name, assembly
479            )));
480        }
481        let mut out = Vec::new();
482        // `iter` must start null; Mono advances it and returns null when done.
483        let mut iter: Ptr = std::ptr::null_mut();
484        loop {
485            let method = unsafe { (self.api.class_get_methods)(class, &mut iter) };
486            if method.is_null() {
487                break;
488            }
489            out.push(cstr(unsafe { (self.api.method_get_name)(method) }));
490        }
491        Ok(out)
492    }
493
494    /// Resolves and caches the three `System.Collections` enumerator methods
495    /// (`IEnumerable::GetEnumerator`, `IEnumerator::MoveNext`,
496    /// `IEnumerator::get_Current`) from Mono's corlib, so `enumerate` does no
497    /// per-call lookups. Idempotent.
498    fn enum_methods(&self) -> Result<&EnumMethods> {
499        if let Some(methods) = self.enum_methods.get() {
500            return Ok(methods);
501        }
502        self.attach_thread();
503        let corlib = unsafe { (self.api.get_corlib)() };
504        if corlib.is_null() {
505            return Err(Error::Other("mono_get_corlib returned null".into()));
506        }
507        let resolve = |ns: &str, ty: &str, m: &str| -> Result<usize> {
508            let (ns_c, ty_c, m_c) = (cstring(ns)?, cstring(ty)?, cstring(m)?);
509            unsafe {
510                let class = (self.api.class_from_name)(corlib, ns_c.as_ptr(), ty_c.as_ptr());
511                if class.is_null() {
512                    return Err(Error::NotFound(format!("corlib type {}.{}", ns, ty)));
513                }
514                let method = (self.api.class_get_method_from_name)(class, m_c.as_ptr(), 0);
515                if method.is_null() {
516                    return Err(Error::NotFound(format!(
517                        "corlib method {}.{}::{}",
518                        ns, ty, m
519                    )));
520                }
521                Ok(method as usize)
522            }
523        };
524        let methods = EnumMethods {
525            get_enumerator: resolve("System.Collections", "IEnumerable", "GetEnumerator")?,
526            move_next: resolve("System.Collections", "IEnumerator", "MoveNext")?,
527            get_current: resolve("System.Collections", "IEnumerator", "get_Current")?,
528        };
529        Ok(self.enum_methods.get_or_init(|| methods))
530    }
531
532    /// Invokes `method` virtually on `target`: resolves the concrete override
533    /// with `mono_object_get_virtual_method`, then `mono_runtime_invoke` with no
534    /// arguments. Returns `None` if the method can't be resolved or the call
535    /// threw a managed exception; otherwise the (possibly null) returned object.
536    ///
537    /// # Safety
538    /// `target` must be a live `MonoObject*` and `method` a `MonoMethod*`
539    /// applicable to it. Each call is a GC safepoint.
540    unsafe fn invoke_virtual(&self, target: Ptr, method: Ptr) -> Option<Ptr> {
541        let concrete = (self.api.object_get_virtual_method)(target, method);
542        if concrete.is_null() {
543            return None;
544        }
545        let mut exc: Ptr = std::ptr::null_mut();
546        let result = (self.api.runtime_invoke)(concrete, target, std::ptr::null_mut(), &mut exc);
547        if exc.is_null() {
548            Some(result)
549        } else {
550            None
551        }
552    }
553
554    /// Resolves and caches the enumerator methods so [`enumerate`](Self::enumerate)
555    /// does no corlib lookups per call. `enumerate` resolves them lazily too, so
556    /// this is only an optimisation and is always safe to skip.
557    pub fn warm_enumerate(&self) -> Result<()> {
558        self.enum_methods()?;
559        Ok(())
560    }
561
562    /// Materializes any managed `IEnumerable` into the addresses of its
563    /// elements, by driving the enumerator through the embedding API:
564    /// `GetEnumerator`, then `MoveNext`/`get_Current` until `MoveNext` is false.
565    ///
566    /// Each element address is a live `MonoObject*`. Unlike CoreCLR's one-shot
567    /// `object[]` read, Mono's SGen is a moving collector and every
568    /// `mono_runtime_invoke` here is a GC safepoint, so a returned address is
569    /// only valid until the next GC — the same raw-pointer contract as the rest
570    /// of this Mono backend. Read or pin what you need before iterating further.
571    pub fn enumerate(&self, obj: usize) -> Result<Vec<usize>> {
572        self.attach_thread();
573        if obj == 0 {
574            return Ok(Vec::new());
575        }
576        let methods = self.enum_methods()?;
577        let target = obj as Ptr;
578        // GetEnumerator -> the enumerator object (boxed when it is a struct).
579        let enumerator = match unsafe { self.invoke_virtual(target, methods.get_enumerator as Ptr) }
580        {
581            Some(e) if !e.is_null() => e,
582            _ => return Ok(Vec::new()),
583        };
584        let mut out = Vec::new();
585        loop {
586            // MoveNext -> a boxed bool; unbox and read the byte.
587            let moved = match unsafe { self.invoke_virtual(enumerator, methods.move_next as Ptr) } {
588                Some(m) if !m.is_null() => m,
589                _ => break,
590            };
591            let unboxed = unsafe { (self.api.object_unbox)(moved) };
592            if unboxed.is_null() || unsafe { std::ptr::read(unboxed as *const u8) } == 0 {
593                break;
594            }
595            // get_Current -> the element (a reference type, returned directly).
596            match unsafe { self.invoke_virtual(enumerator, methods.get_current as Ptr) } {
597                Some(current) => out.push(current as usize),
598                None => break,
599            }
600        }
601        Ok(out)
602    }
603}