分配内存并调用C ++回调的Rust函数崩溃 [英] Rust function that allocates memory and calls a C++ callback crashes

查看:98
本文介绍了分配内存并调用C ++回调的Rust函数崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

锈迹代码:

#[repr(C)]
pub struct Tmp {
    pub callback: extern "C" fn(i: i32),
}

#[no_mangle]
pub extern "C" fn set_callback(callback: extern "C" fn(i: i32)) -> *mut Tmp {
    let mut tmp = Box::new(Tmp { callback });
    println!("tmp as ptr: {:p}", tmp); // >> here <<
    &mut *tmp
}

#[no_mangle]
pub extern "C" fn use_callback(tmp_ptr: *mut Tmp) {
    unsafe {
        ((*tmp_ptr).callback)(1);
        ((*tmp_ptr).callback)(3);
    }
}

C ++代码:

struct Tmp {
    void (*callback)(int32_t);
};

typedef Tmp*(__stdcall* set_callback_t)(void(*callback_t)(int32_t));
typedef void(__stdcall* use_callback_t)(Tmp*);

void callback(int32_t i) {
    printf("%d\n", i * 2);
}

int main() {
    // ... loading rust part as .dll
    // ... checking if loaded correctly
    Tmp* tmp_ptr = set_callback(callback);
    printf("tmp_ptr %p\n", tmp_ptr);
    use_callback(tmp_ptr);
    // ... freeing the .dll
}

当我编译该程序时,它会按预期工作. Rust和C ++中指向Tmp结构的指针的打印值匹配.当我在Rust中注释println时,C ++程序崩溃,这意味着此(可能是Rust部分)代码出了点问题.

When I compile this the program, it works as expected. The printed values of pointer to Tmp structure in Rust and C++ match. When I comment out the println in Rust, the C++ program crashes, which means that there is something wrong with this (probably Rust part) code.

我正在使用Rust代码作为.dll.我想将指向C ++函数的指针传递给set_callback函数,然后当我在C ++代码中调用use_callback时在use_callback函数中使用该指针.

I am using the Rust code as a .dll. I would like to pass a pointer to C++ function to the set_callback function, and then I would like to use that pointer in the use_callback function when I call use_callback in the C++ code.

据我所知,最后我将不得不调用Rust函数来删除Tmp结构,但我将其遗漏了.

For what I understand, at the end I will have to call a Rust function to drop the Tmp structure, but I left that out.

推荐答案

Box与C ++中的std::unique_ptr相似.构造tmp的方式将在函数末尾释放所指向的数据.

Box in Rust is similar to std::unique_ptr in C++. The way you construct tmp, the data pointed to will be freed at the end of the function.

为了将指针泄漏"到C ++世界中,应使用 Box::into_raw .

In order to "leak" the pointer into C++ world, you should use Box::into_raw.

请注意,由于不能保证Rust和C ++以相同的方式分配内存;您将必须将指针传递回Rust并使用 Box::from_raw 取消分配.

Note that as there is no guarantee that Rust and C++ allocate memory the same way; you will have to pass the pointer back to Rust and use Box::from_raw to deallocate it.

这篇关于分配内存并调用C ++回调的Rust函数崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆