将 R 对象传递给 Rust 程序需要哪些步骤? [英] What are the steps necessary to pass R objects to a Rust program?

查看:38
本文介绍了将 R 对象传递给 Rust 程序需要哪些步骤?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

R 和 Rust 都可以与 C 代码接口,所以我认为这是非常可能的.不过,我有点不清楚如何继续.

Both R and Rust can interface with C code, so I think it is very possible. I am a bit unclear about how to proceed, however.

我已阅读这些部分以寻找答案:

I have read these sections looking for answers:

  1. R-extensions 系统和外语接口
  2. Rust 外部函数接口指南

虽然我精通 R,但我不是系统程序员,并且对构建链的样子感到困惑以进行这种努力.

But while I am well-versed in R I am not a systems programmer and confused by what the build-chain looks like for such an endeavor.

使用 Rinternals.h 将是理想的,但我也会满足于更简单的 .C 接口.

Using Rinternals.h would be ideal, but I would settle for the simpler .C interface as well.

推荐答案

如果 R 可以与 C 代码接口,那么从暴露 C 风格函数的 Rust 代码编译共享库完全没有问题.

If R can interface with C code, so it is no problem at all to compile shared library from Rust code which exposes C-style functions.

然后您就可以轻松地使用您的库,因为它是用 C 或 C++ 编写的.当然,你不能直接从 R 中使用 Rust 对象和库,你必须制作适当的 C 接口来转换它们的功能.

Then you can easily use your library as it was written in C or C++. Of course, you will not able to use Rust object and libraries directly from R, you will have to make appropriate C interface for converting their functions.

这是我如何为 SBCL 做到这一点,我想对于 R 来说会非常相似:

Here is how can I do that for SBCL, and I suppose it would be very similar for R:

一些代码:

% cat Experiment.rs

extern crate libc;

use libc::{c_int, c_char};
use std::{ffi, str};

#[no_mangle]
pub extern fn rust_code_string_to_int(s: *const c_char, r: *mut c_int) -> c_int { 
    let string = String::from_utf8_lossy(unsafe { ffi::CStr::from_ptr(s).to_bytes() });
    match <isize as str::FromStr>::from_str(&*string) {
        Ok(value) => { unsafe { *r = value as c_int }; 0 },
        Err(_) => -1,
    }
}

然后我正在制作共享库:

Then I'm making shared lib:

% rustc --crate-type dylib experiment.rs
% nm -a libexperiment.dylib | grep rust_code_string_to_int
0000000000001630 t __ZN23rust_code_string_to_int10__rust_abiE
00000000000015e0 T _rust_code_string_to_int

接下来,在 SBCL 方面

现在我只是加载我的共享库,然后我可以访问我的 rust_code_string_to_int 函数:

RUST> (sb-alien:load-shared-object "libexperiment.dylib")
#P"libexperiment.dylib"
RUST> (sb-alien:with-alien ((result sb-alien:int 0))  
          (values (sb-alien:alien-funcall (sb-alien:extern-alien "rust_code_string_to_int" 
                                                                 (sb-alien:function sb-alien:int 
                                                                                    (sb-alien:c-string :external-format :utf-8)
                                                                                    (sb-alien:* sb-alien:int)))
                                          (sb-alien:make-alien-string "42")
                                          (sb-alien:addr result))
                  result))
0
42

这篇关于将 R 对象传递给 Rust 程序需要哪些步骤?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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