引用的静态变量中的错误值

wrong value in referenced static variable

我正在尝试从 WebAssembly 模块更新 Rust 中的静态变量,该模块本身是用 Rust 编写的。

为了设置变量,我编写了一个函数init并将其导出到 WASM 模块:

static mut FILE_NAME: &str = "";

#[no_mangle]
pub fn init(model_path: *mut c_char) {
    let path = unsafe { CStr::from_ptr(model_path).to_str().unwrap() };
    unsafe {
        FILE_NAME = path;
        println!("{}", FILE_NAME);
    }
}

然后我尝试从另一个导出函数访问它load_model:

#[no_mangle]
pub fn load_model() -> *mut c_char {
    let path = unsafe { &FILE_NAME };
    println!("{}", path);
    // stuff ...
}

当使用指向 "/lib/python/iris_knn.model" 的指针作为参数调用 init 函数然后调用 load_model 函数时,我打印了以下行:

lib/python/iris_knn.model
?4?on/iknn.mode

这当然不是我所期待的。这里有什么问题?

附带说明一下,我知道这是不好的做法,但我更认为这是一种学习。

感谢@Cerberus 的评论,我发现了自己的错误。在调用 init 之后,我立即释放了与传递的字符串关联的内存。从 load_model.

访问时,内存已释放且不再有效

以下是正确的主机运行时代码的摘录:

# ...
instance = Instance(module, import_object)
(file_ptr, file_len) = get_string_ptr('/lib/python/iris_knn.model', instance)
instance.exports.init(file_ptr)
# the next line is wrong and to be removed
# instance.exports.deallocate(file_ptr, file_len)

def load_model():
    output_ptr = instance.exports.load_model()
    (output, output_len) = get_string_from_ptr(output_ptr, instance)
    instance.exports.deallocate(output_ptr, output_len)
    return output