【问题标题】:How to dereference C/C++ void * to struct or callback in Rust?如何取消引用 C/C++ void * 到 Rust 中的结构或回调?
【发布时间】:2020-10-09 18:16:51
【问题描述】:

我想用 Rust 为一个老游戏写一个 AI。该游戏的 AI 是库,在其 Linux 端口中它只是一个 .so 文件导出:

extern "C" void client(int Command, int Player, void *Data);

void *Data 可以是结构体(取决于Command)或这个函数:

typedef int TServerCall(int Command, int Player, int Subject, void *Data);

在 C++ 中,AI 代码根据命令将其转换为已知大小或回调的结构,例如:

typedef int __stdcall TServerCall(int Command, int Player, int Subject, void *Data);

或结构:

// where G is a extern TNewGameData G;

G = *(TNewGameData *) Data;

然后我可以访问G 或其他结构或数组的字段。

问题:

如何将 void * 形式的数据转换为 Rust 中的结构或函数?

【问题讨论】:

标签: c++ rust ffi


【解决方案1】:

您可以在 Rust 中强制转换原始指针。

use libc::{c_void, c_int};

#[repr(C)]
struct TNewGameData {
    // the fields go here
}

#[no_mangle]
pub extern "C" fn client(command: c_int, player: c_int, data: *mut c_void) {
    // Cast raw pointer to the right type.
    let game_data_ptr = data as *mut TNewGameData;
    // Convert to Rust reference.
    let game_data = unsafe { &mut *data };
}

【讨论】:

  • 我可以使用这种方法将其转换为函数吗?
猜你喜欢
  • 1970-01-01
  • 2014-07-23
  • 1970-01-01
  • 1970-01-01
  • 2010-09-22
  • 2011-06-17
  • 2017-01-13
  • 2011-07-20
  • 2012-05-23
相关资源
最近更新 更多