使用 Rust bindgen 链接头文件的问题

Problems linking header files with Rust bindgen

根据 https://rust-lang.github.io/rust-bindgen/tutorial-3.html 上的 Rust bindgen 教程,我正在尝试为现有的 C 头文件生成 FFI。但是,我在链接头文件时遇到问题。

https://github.com/studersi/rust-test-apache 的存储库包含重现问题所需的所有文件,包括包含必要命令的 README 文件。最相关的文件列在问题的末尾。

我正在使用 Docker 容器构建项目(请参阅下面的 Docker 文件)。 C头文件是从网上下载的,放在子目录downloads/.

链接器的包含(请参阅下面的 build.rs)基于 apxs 工具用于根据我的项目所在的 Apache httpd module development guide 构建类似 C 示例的包含是根据。

$ apxs -a -c mod_example.c
/usr/share/apr-1.0/build/libtool  --mode=compile --tag=disable-static x86_64-linux-gnu-gcc -prefer-pic -pipe -g -O2 -fstack-protector-strong -Wformat -Werror=format-security  -Wdate-time -D_FORTIFY_SOURCE=2   -DLINUX -D_REENTRANT -D_GNU_SOURCE  -pthread  -I/usr/include/apache2  -I/usr/include/apr-1.0   -I/usr/include/apr-1.0 -I/usr/include  -c -o mod_example.lo mod_example.c && touch mod_example.slo
libtool: compile:  x86_64-linux-gnu-gcc -pipe -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -DLINUX -D_REENTRANT -D_GNU_SOURCE -pthread -I/usr/include/apache2 -I/usr/include/apr-1.0 -I/usr/include/apr-1.0 -I/usr/include -c mod_example.c  -fPIC -DPIC -o .libs/mod_example.o
/usr/share/apr-1.0/build/libtool  --mode=link --tag=disable-static x86_64-linux-gnu-gcc -Wl,--as-needed -Wl,-z,relro -Wl,-z,now    -o mod_example.la  -rpath /usr/lib/apache2/modules -module -avoid-version    mod_example.lo
libtool: link: x86_64-linux-gnu-gcc -shared  -fPIC -DPIC  .libs/mod_example.o    -Wl,--as-needed -Wl,-z -Wl,relro -Wl,-z -Wl,now   -Wl,-soname -Wl,mod_example.so -o .libs/mod_example.so
libtool: link: ( cd ".libs" && rm -f "mod_example.la" && ln -s "../mod_example.la" "mod_example.la" )

启动容器并构建Cargo项目后,报错找不到要转换的头文件

$ cargo build
   Compiling mod_rs v0.1.0 (/home/rustacian/mod_rs)
error: failed to run custom build command for `mod_rs v0.1.0 (/home/rustacian/mod_rs)`

Caused by:
  process didn't exit successfully: `/home/rustacian/mod_rs/target/debug/build/mod_rs-a68981041b3e3908/build-script-build` (exit code: 101)
  --- stdout
  cargo:include=/home/rustacian/downloads/httpd-2.4.46/include
  cargo:include=/home/rustacian/downloads/apr-1.7.0/include
  cargo:include=/usr/include/apache2
  cargo:include=/usr/include/apr-1.0
  cargo:rerun-if-changed=wrapper.h

  --- stderr
  wrapper.h:2:10: fatal error: 'apr_hash.h' file not found
  wrapper.h:2:10: fatal error: 'apr_hash.h' file not found, err: true
  thread 'main' panicked at 'Unable to generate bindings: ()', build.rs:34:10
  note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

请注意,我已经尝试使用不同的命令(cargo:include.clang_arg)并从不同的位置(手动下载并使用系统包安装)包含头文件,但到目前为止没有任何效果。

[...]
    println!("cargo:include=/home/rustacian/downloads/httpd-2.4.46/include");
    println!("cargo:include=/home/rustacian/downloads/apr-1.7.0/include");
    println!("cargo:include=/usr/include/apache2");
    println!("cargo:include=/usr/include/apr-1.0");
[...]
        .clang_arg("-I/usr/include/apache2 -I/usr/include/apr-1.0 -I/home/rustacian/downloads/httpd-2.4.46/include -I/home/rustacian/downloads/apr-1.7.0/include")
[...]

为什么bindgen找不到头文件?如有任何帮助,我们将不胜感激。


Docker文件

FROM rust

ARG USERNAME="rustacian"

RUN apt-get update
RUN apt-get -y install --no-install-recommends apache2-dev llvm librust-bindgen-dev

RUN groupadd -r ${USERNAME} && useradd -s /bin/bash -g ${USERNAME} ${USERNAME}
USER ${USERNAME}

WORKDIR /home/${USERNAME}

build.rs

extern crate bindgen;

use std::env;
use std::path::PathBuf;

fn main() {
    // Tell cargo to tell rustc to link the
    // shared library.
    println!("cargo:include=/home/rustacian/downloads/httpd-2.4.46/include");
    println!("cargo:include=/home/rustacian/downloads/apr-1.7.0/include");
    println!("cargo:include=/usr/include/apache2");
    println!("cargo:include=/usr/include/apr-1.0");

    // Tell cargo to invalidate the built crate whenever the wrapper changes
    println!("cargo:rerun-if-changed=wrapper.h");

    // The bindgen::Builder is the main entry point
    // to bindgen, and lets you build up options for
    // the resulting bindings.
    let bindings = bindgen::Builder::default()
        // The input header we would like to generate
        // bindings for.
        .header("wrapper.h")
        // Add the includes for C header files.
        // Derived from https://httpd.apache.org/docs/2.4/developer/modguide.html
        // $ apxs -a -c mod_example.c
        .clang_arg("-I/usr/include/apache2 -I/usr/include/apr-1.0 -I/home/rustacian/downloads/httpd-2.4.46/include -I/home/rustacian/downloads/apr-1.7.0/include")
        // Tell cargo to invalidate the built crate whenever any of the
        // included header files changed.
        .parse_callbacks(Box::new(bindgen::CargoCallbacks))
        // Finish the builder and generate the bindings.
        .generate()
        // Unwrap the Result and panic on failure.
        .expect("Unable to generate bindings");

    // Write the bindings to the $OUT_DIR/bindings.rs file.
    let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
    bindings
        .write_to_file(out_path.join("bindings.rs"))
        .expect("Couldn't write bindings!");
}

wrapper.h

#include "stdio.h"
#include "apr_hash.h"
#include "ap_config.h"
#include "ap_provider.h"
#include "httpd.h"
#include "http_core.h"
#include "http_config.h"
#include "http_log.h"
#include "http_protocol.h"
#include "http_request.h"

Cargo.toml

[package]
name = "mod_rs"
version = "0.1.0"
authors = ["studersi <*****@******.***>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
libc = "*"

[build-dependencies]
bindgen = "*"

在这里发布问题后很快找到了答案。

问题在于 .clang_arg() 调用。每次对该函数的调用只能有一个包含,但允许对该函数进行多次调用。

工作 build.rs 将包括以下调用:

        .clang_arg("-I/usr/include/apache2")
        .clang_arg("-I/usr/include/apr-1.0")

不需要进一步包含,我现在可以构建项目,生成绑定。

$ cargo build
   Compiling mod_rs v0.1.0 (/home/rustacian/mod_rs)
    Finished dev [unoptimized + debuginfo] target(s) in 9.24s
$ find . -name bindings.rs
./target/debug/build/mod_rs-ba1afe54e266aa8f/out/bindings.rs
$ head -c 1000 ./target/debug/build/mod_rs-ba1afe54e266aa8f/out/bindings.rs
/* automatically generated by rust-bindgen */

# [repr (C)] # [derive (Copy , Clone , Debug , Default , Eq , Hash , Ord , PartialEq , PartialOrd)] pub struct __BindgenBitfieldUnit < Storage , Align > { storage : Storage , align : [Align ; 0] , } impl < Storage , Align > __BindgenBitfieldUnit < Storage , Align > { # [inline] pub const fn new (storage : Storage) -> Self { Self { storage , align : [] } } } impl < Storage , Align > __BindgenBitfieldUnit < Storage , Align > where Storage : AsRef < [u8] > + AsMut < [u8] >, { # [inline] pub fn get_bit (& self , index : usize) -> bool { debug_assert ! (index / 8 < self . storage . as_ref () . len ()) ; let byte_index = index / 8 ; let byte = self . storage . as_ref () [byte_index] ; let bit_index = if cfg ! (target_endian = "big") { 7 - (index % 8) } else { index % 8 } ; let mask = 1 << bit_index ; byte & mask == mask } # [inline] pub fn set_bit (& mut self , index : usize , val : bool) { debug_assert ! (index / 8 < self . storage . as_ref ()