如何使用 Rust 中的 C typedef 结构和函数?

How to use a C typedef struct and functions with that struct from Rust?

我有这些 C 文件,我想使用 Rust 中的 pair_addaddPAIR

adder.c

#include <stdlib.h>
#include "adder.h"

int pair_add(PAIR * ppair) {
    return ppair->x + ppair->y;
}

int add(int x, int y) {
    return x + y;
}

adder.h

typedef struct {
    int x;
    int y;
} PAIR;

int pair_add(PAIR * ppair);
int add(int, int);

我编译它们使用:

gcc -c adder.c
ar rc libadder.a adder.o  # Static link

documentation does not detail how to integrate C typedef structs and the example is for functions which return and accept i32. Other online resources were also limited.

我尝试了以下但无法添加 PAIR 类型定义:

extern crate libc;

use libc::c_int;

#[link(name = "adder")]
extern "C" {
    // Define PAIR

    // int pair_add(PAIR * ppair);
    fn pair_add(input: Pair) -> c_int;

    // int add(int, int);
    fn add(input1: c_int) -> c_int;
}

fn main() {}

第一个:

typedef struct {
    int x;
    int y;
} PAIR;

这声明了一个匿名结构,目前 Rust 不支持它。有RFC提议增加匿名类型

其次,typedef 只是一个别名,结构的名称对于兼容性并不重要。这意味着你可以简单地做:

extern crate libc;
use libc::c_int;

#[repr(C)]
struct PAIR {
    x: c_int,
    y: c_int,
}

// optional "equivalent" of typedef
type Pair = PAIR;

extern "C" {
    fn pair_add(input: *mut Pair) -> c_int;
    // could be
    // fn pair_add(input: *mut PAIR) -> c_int;
}

您可以轻松地忽略 typedef 并只使用 PAIR 作为该结构的名称。您甚至可以只写 struct PAIR; 使其不透明。