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)]
34pub struct ModuleObj {
35    object: Object,
36}
37
38/// ABI-stable owned Module for FFI operations.
39#[repr(C)]
40#[derive(ObjectRef, Clone)]
41pub struct Module {
42    data: ObjectArc<ModuleObj>,
43}
44
45impl Module {
46    /// Load a module from a dynamic library file.
47    ///
48    /// # Arguments
49    /// * `file_name` - Path to the dynamic library file to load
50    ///
51    /// # Returns
52    /// * `Result<Module>` - A `Module` instance on success
53    pub fn load_from_file<Str: AsRef<str>>(file_name: Str) -> Result<Module> {
54        static API_FUNC: std::sync::LazyLock<Function> =
55            std::sync::LazyLock::new(|| Function::get_global("ffi.ModuleLoadFromFile").unwrap());
56        let file_name = crate::string::String::from(file_name);
57        (*API_FUNC)
58            .call_tuple_with_len::<1, _>((file_name,))?
59            .try_into()
60    }
61
62    /// Get a function from the module by name.
63    ///
64    /// # Arguments
65    /// * `name` - The name of the function to retrieve
66    ///
67    /// # Returns
68    /// * `Result<Function>` - A `Function` instance on success
69    pub fn get_function<Str: AsRef<str>>(&self, name: Str) -> Result<Function> {
70        static API_FUNC: std::sync::LazyLock<Function> =
71            std::sync::LazyLock::new(|| Function::get_global("ffi.ModuleGetFunction").unwrap());
72        let name = crate::string::String::from(name);
73        (*API_FUNC)
74            .call_tuple_with_len::<3, _>((self, name, true))?
75            .try_into()
76    }
77}