Skip to main content

tvm_ffi/extra/
module.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19use crate::derive::{Object, ObjectRef};
20use crate::error::Result;
21use crate::function::Function;
22use crate::object::{Object, ObjectArc};
23use tvm_ffi_sys::TVMFFITypeIndex as TypeIndex;
24
25//-----------------------------------------------------
26// Module
27//-----------------------------------------------------
28
29/// A TVM FFI Module for loading dynamic libraries and retrieving functions.
30#[repr(C)]
31#[derive(Object)]
32#[type_key = "ffi.Module"]
33#[type_index(TypeIndex::kTVMFFIModule)]
34#[type_final]
35pub struct ModuleObj {
36    object: Object,
37}
38
39/// ABI-stable owned Module for FFI operations.
40#[repr(C)]
41#[derive(ObjectRef, Clone)]
42pub struct Module {
43    data: ObjectArc<ModuleObj>,
44}
45
46impl Module {
47    /// Load a module from a dynamic library file.
48    ///
49    /// # Arguments
50    /// * `file_name` - Path to the dynamic library file to load
51    ///
52    /// # Returns
53    /// * `Result<Module>` - A `Module` instance on success
54    pub fn load_from_file<Str: AsRef<str>>(file_name: Str) -> Result<Module> {
55        let file_name = crate::string::String::from(file_name);
56        crate::cached_global_func!("ffi.ModuleLoadFromFile")
57            .call_tuple_with_len::<1, _>((file_name,))?
58            .try_into()
59    }
60
61    /// Get a function from the module by name.
62    ///
63    /// # Arguments
64    /// * `name` - The name of the function to retrieve
65    ///
66    /// # Returns
67    /// * `Result<Function>` - A `Function` instance on success
68    pub fn get_function<Str: AsRef<str>>(&self, name: Str) -> Result<Function> {
69        let name = crate::string::String::from(name);
70        crate::cached_global_func!("ffi.ModuleGetFunction")
71            .call_tuple_with_len::<3, _>((self, name, true))?
72            .try_into()
73    }
74}