如何将切片的每个元素作为单独的参数传递给可变参数 C 函数? [英] How do I pass each element of a slice as a separate argument to a variadic C function?

查看:62
本文介绍了如何将切片的每个元素作为单独的参数传递给可变参数 C 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Rust 构建一个 Redis 模块.我找到了一些很好的例子,但是在处理应该接受可变参数的 C 函数接口时我被卡住了.

I'm building a Redis Module in Rust. I've found some good examples, but I'm stuck when dealing with interfacing a C function that is supposed to accept variadic arguments.

Redis Module C SDK 有一个名为 RedisModule_Call 的函数,它接受一些特定的参数,然后是表示 Redis 命令的 n 参数.来自 Redis 模块 SDK 文档(C 语言):

The Redis Module C SDK has a function called RedisModule_Call which accepts a few specific arguments then n arguments that represent a Redis command. From the Redis Module SDK documentation (in C):

RedisModuleCallReply *reply;
reply = RedisModule_Call(ctx,"INCR","sc",argv[1],"10");

RedisModule_Call 的前三个参数是特定的,但其余的代表 Redis 命令,很容易有数百个参数.

RedisModule_Call's first three arguments are specific, but the rest represent Redis commands that could easily have hundreds of arguments.

在 Rust 中,我遵循 Redis-Cell 中的模式,这是一个 Redis模块在 Rust 中实现(成功).该模块非常棒,但处理这个特定问题的方法非常有限.实际上,它以某种蛮力的方式最多接受三个参数:

In Rust, I'm following the patterns in Redis-Cell which is a Redis module implemented (successfully) in Rust. The module is fantastic but has a very limited way of dealing with this particular problem. Effectively, it accepts up to three arguments in a somewhat brute force way:

pub fn call(&self, command: &str, args: &[&str]) -> Result<Reply, CellError> {
   // ... code ... 
   let raw_reply = match args.len() {
        1 => raw::call1::call(/* ... */),
        2 => raw::call2::call(/* ... */),
        // ...

这些 call1call2 函数实际上只是处理不同参数长度的存根:

These call1 and call2 functions are practically just stubs that handle the different argument lengths:

pub mod call2 {
    use redis::raw;

    pub fn call(
        ctx: *mut raw::RedisModuleCtx,
        cmdname: *const u8,
        fmt: *const u8,
        arg0: *mut raw::RedisModuleString,
        arg1: *mut raw::RedisModuleString,
    ) -> *mut raw::RedisModuleCallReply {
        unsafe { RedisModule_Call(ctx, cmdname, fmt, arg0, arg1) }
    }

    #[allow(improper_ctypes)]
    extern "C" {
        pub static RedisModule_Call: extern "C" fn(
            ctx: *mut raw::RedisModuleCtx,
            cmdname: *const u8,
            fmt: *const u8,
            arg0: *mut raw::RedisModuleString,
            arg1: *mut raw::RedisModuleString,
        ) -> *mut raw::RedisModuleCallReply;
    }
}

我需要能够传入 n 参数,n 是在运行时确定的,因此这种硬编码方法不实用.我知道 Rust 对可变参数函数的支持有限,并且我一直在阅读有关 RFC 2137 的一些资料,但我不确定这是否适用.

I need to be able to pass in n arguments, with n being determined at run time, so this method of hard coding isn't practical. I know Rust has limited support for variadic functions and I've been doing some reading about RFC 2137, but I'm not sure this applies.

我正在寻找一种方法将参数向量应用到 RedisModule_Call 的末尾或类似参数的扩展语法.我对 Rust 比较陌生,但我已经搜索了又搜索,我似乎找不到任何方法可以在 Rust 中解决这个问题.

I'm looking for a way to apply an argument vector to the end of RedisModule_Call or something like a spread syntax for the arguments. I'm relatively new to Rust but I've searched and searched and I can't seem to find any way to scratch this itch in Rust.

澄清 - 我可以将参数传递到 RedisModule_Call(这是可变参数)没问题,但我找不到一种语法方式将 Rust 中的可变数量的参数传递到 C 函数中.我想要完成的是这样的:

To clarify - I can pass arguments into RedisModule_Call (which is variadic) no problem, but I can't find a syntactical way to pass in a variable number of arguments in Rust into the C function. What I'm trying to accomplish is something like this:

impl Redis {
    pub fn call(&self, command: &str, args: &[&str]) -> Result<Reply, CellError> {
        /* ... */

       unsafe { RedisModule_Call(ctx, cmdname, fmt, ...args) }
       /* ... */ 

其中 ...args 是某种黑魔法,它允许 args 表示 1 个参数或 100,这相当于 RedisModule_Call(ctx, cmdname, fmt, args[0], args[1]/* ... 等等 */).

Where ...args is some sort of black magic to that would allow args to represent 1 argument or 100 which would be the equivalent of RedisModule_Call(ctx, cmdname, fmt, args[0], args[1] /* ... and so on */).

推荐答案

没有,至少现在没有,我打赌可能永远不会.

You don't, at least not yet, and I'd wager probably never.

要做到这一点,您需要两个关键能力,这两个能力都不在您的控制范围内:

To be able to do this, you'd need two key abilities, both of which are outside of your control:

  1. Redis 需要提供一个接受 va_list 参数的函数,而不仅仅是一个 ....

  1. Redis needs to provide a function that accepts a va_list argument, not just a ....

奇怪的是,Redis 还没有提供这样的功能,但这也许是其他实现模块的人完全避免了这个问题的迹象.

It's strange that Redis doesn't already provide such a function, but perhaps this is a sign that other people implementing modules avoid the problem entirely.

Rust 需要提供一种方法来构造 va_list 参数.

Rust needs to provide a way to construct the va_list argument.

虽然它看起来像 RFC 2137将引入 VaList 类型,提议的 API 不提供在其中创建一个组值的方法.

While it looks like RFC 2137 will introduce a VaList type, the proposed API does not provide a way to create one or set values in it.

请注意,您即使在 C 中也无法做您想做的事(至少不容易或可移植).

Note that you can't do what you want, even in C (at least not easily or portably).

你能做些什么呢?假设您正在实现使用可变参数的代码,您可以从调用中删除变体.C 中的项目集合只是一个指针和一个长度,所以改为传递它:

What can you do instead? Assuming that you are implementing the code that consumes the variadic arguments, you can remove the variation from your call. A collection of items in C is just a pointer and a length, so pass that instead:

extern "C" {
    fn call(n_args: i32, ...);
}

fn x(args: &[i32]) {
    unsafe { call(2, args.len(), args.as_ptr()) };
}

如果您无法控制另一侧读取代码的内容,一个可能的(读作:可怕)想法是在一些足够大"的代码上进行模式匹配.切片的子集并分派给可变参数函数:

If you didn't have control of what reads the code on the other side, one possible (read: terrible) idea is to pattern match on some "large enough" subset of the slice and dispatch off to the variadic function:

extern "C" {
    fn call(n_args: i32, ...);
}

fn x(args: &[i32]) {
    unsafe {
        match args {
            [] => call(0),
            [a] => call(1, a),
            [a, b] => call(2, a, b),
            _ => panic!("Didn't implement this yet"),
        }
    }
}

另见:

这篇关于如何将切片的每个元素作为单独的参数传递给可变参数 C 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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