【发布时间】:2014-10-17 06:03:08
【问题描述】:
我正在考虑用 Rust 编写一个 Ruby gem。假设我想在 Rust 中创建一些结构,这些结构返回到类似于示例here 的 Ruby 代码。在将 Point 结构添加到我的 Ruby 代码时,我想直接调用它的属性。目前我将不得不做这样的事情:
point.rb:
require "fiddle"
require "fiddle/import"
module RustPoint
extend Fiddle::Importer
dlload "./libmain.dylib"
extern "Point* make_point(int, int)"
extern "double get_distance(Point*, Point*)"
extern "int y(Point*)"
extern "int x(Point*)"
end
main.rs:
use std::num::pow;
pub struct Point { x: int, y: int }
#[no_mangle]
pub extern "C" fn make_point(x: int, y: int) -> Box<Point> {
box Point { x: x, y: y }
}
#[no_mangle]
pub extern "C" fn x(p: &Point) -> int {
p.x
}
#[no_mangle]
pub extern "C" fn y(p: &Point) -> int {
p.y
}
并在 Ruby 中使用它:
point = RustPoint::make_point(0, 42)
# To get x:
x = RustPoint::x(point)
得到一个 x 值。我更喜欢这样的东西:
point = RustPoint::make_point(0, 42)
# To get x:
x = point.x
有没有人知道一个库或一种更容易实现的方法。我认为如果我不会看到与红宝石方面的点对象不同的情况会更好。如果这是一个 C 扩展、一个 Ruby 对象或用 Rust 编写,我不应该有所作为。
编辑:我希望 Rust 代码表现得像原生扩展。因此返回的结构应该可以从 Ruby 端调用,类似于使用 ruby 对象作为值的 C 结构。当然,处理 rust 代码中的 ruby 对象需要一个库。
【问题讨论】: