首页 > 解决方案 > 如何为 FFI 创建一个包含可为空函数指针的结构?

问题描述

我有一个加载共享库插件的现有 C 程序。主 C 程序通过包含整数、字符串、函数指针等的 C 结构与这些插件交互。如何从 Rust 创建这样的插件?

请注意,(真正的)C 程序无法更改,API 也无法更改,它们是固定的,现有的东西,所以这不是关于“如何最好地支持 Rust 中的插件”的问题,而是 Rust 如何制作*.so文件与现有的 C 程序互操作。

这是一个 C 程序 + C 插件的简化示例:

/* gcc -g -Wall test.c -o test -ldl
   ./test ./test-api.so
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <dlfcn.h>

struct api {
  uint64_t i64;
  int i;
  const char *name;                /* can be NULL */
  void (*load) (void);             /* must not be NULL */
  void (*hello) (const char *str); /* can be NULL */
};

int
main (int argc, char *argv[])
{
  void *dl = dlopen (argv[1], RTLD_NOW);
  if (!dl) { fprintf (stderr, "%s: %s\n", argv[1], dlerror ()); exit (1); }
  struct api *(*get_api) (void) = dlsym (dl, "get_api");
  printf ("calling get_api ...\n");
  struct api *api = get_api ();
  printf ("api->i64 = %" PRIi64 "\n", api->i64);
  printf ("api->i = %d\n", api->i);
  if (api->name)
    printf ("api->name = %s\n", api->name);
  printf ("calling api->load ...\n");
  api->load ();
  if (api->hello) {
    printf ("calling api->hello ...\n");
    api->hello ("world");
  }
  printf ("exiting\n");
  exit (0);
}
/* gcc -g -shared -fPIC -Wall test-api.c -o test-api.so */

#include <stdio.h>
#include <stdint.h>

static void
load (void)
{
  printf ("this is the load function in the plugin\n");
}

static void
hello (const char *str)
{
  printf ("hello %s\n", str);
}

static struct api {
  uint64_t i64;
  int i;
  const char *name;
  void (*load) (void);
  void (*hello) (const char *str);
} api = {
  1042,
  42,
  "this is the plugin",
  load,
  hello,
};

struct api *
get_api (void)
{
  return &api;
}

这是我在 Rust 中编写的试图获取插件的内容,但它无法编译:

extern crate libc;

use libc::*;
use std::ffi::*;
use std::ptr;
use std::os::raw::c_int;

#[repr(C)]
pub struct api {
    i64: uint64_t,
    i: c_int,

    name: *const c_char,

    load: extern fn (),
    hello: extern fn (), // XXX
}

extern fn hello_load () {
    println! ("hello this is the load method");
}

#[no_mangle]
pub extern fn get_api () -> *const api {
    println! ("hello from the plugin");

    let api = Box::new (api {
        i64: 4201,
        i: 24,
        name: CString::new("hello").unwrap().into_raw(), // XXX memory leak?
        load: hello_load,
        hello: std::ptr::null_mut,
    });

    return Box::into_raw(api); // XXX memory leak?
}

这是使用包含编译Cargo.toml的:

[package]
name = "embed"
version = "0.1.0"

[dependencies]
libc = "0.2"

[lib]
name = "embed"
crate-type = ["cdylib"]

错误是:

error[E0308]: mismatched types
  --> src/lib.rs:32:16
   |
32 |         hello: std::ptr::null_mut,
   |                ^^^^^^^^^^^^^^^^^^ expected "C" fn, found "Rust" fn
   |
   = note: expected type `extern "C" fn()`
              found type `fn() -> *mut _ {std::ptr::null_mut::<_>}`

error: aborting due to previous error

我没有尝试加载模块,但是当我之前用真正的程序尝试过这个时,这些字段都是错误的,表明一些更基本的东西是错误的。

标签: crust

解决方案


tl;dr用于Option表示可为空的函数指针和None用于空。

错误消息令人困惑,首先,因为std::ptr::null_mut它不是指针;它是一个返回指针的通用函数,你还没有调用它。因此,Rust 看到您传递了一个具有错误签名和调用约定的函数,并抱怨这一点。

但是一旦你解决了这个问题,你就会得到这个错误:

error[E0308]: mismatched types
  --> src/lib.rs:29:16
   |
29 |         hello: std::ptr::null_mut(),
   |                ^^^^^^^^^^^^^^^^^^^^ expected fn pointer, found *-ptr
   |
   = note: expected type `extern "C" fn()`
              found type `*mut _`

函数指针和对象指针不兼容(C 中也是这种情况),因此不能在它们之间进行转换。null_mut返回一个对象指针,所以你需要找到另一种方法来创建一个空函数指针。

函数指针(类型的值fn(...) -> _)还有另一个有趣的属性:与原始指针(*const _*mut _)不同,它们不能为空。您不需要unsafe块来通过指针调用函数,因此创建空函数指针是不安全的,就像创建空引用一样。

你如何使某些东西可以为空?把它包起来Option

#[repr(C)]
pub struct api {
    // ...
    load: Option<extern fn ()>,
    hello: Option<extern fn ()>, // assuming hello can also be null
}

Some(function)并用or填充它None

let api = Box::new (api {
    // ...
    load: Some(hello_load),
    hello: None,
});

enum在结构中使用s,包括Option,通常不是一个好主意repr(C),因为 C 没有enum等价物,所以你不知道在另一边会得到什么。但是在Option<T>where Tis something non-nullable的情况下,None由 null 值表示,所以应该没问题。

用于Option表示 FFI 的可空函数指针的使用记录在Unsafe Code Guidelines中:

Rust 函数指针类型不支持 null 值——就像引用一样,期望是您Option用来创建可空指针。Option<fn(Args...) -> Ret>将具有与 完全相同的 ABI fn(Args...) -> Ret,但还允许空指针值。


推荐阅读