使用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容器构建项目(请参阅下面的Dockerfile)。 C头文件是从Internet下载的,并放在子目录downloads/中。

链接器的includes(请参见下面的build.rs)基于apxs工具所包含的includes,该工具用于根据我的项目所基于的Apache httpd module development guide来构建类似的C示例。 / p>

$ 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,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,-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无法找到头文件?任何帮助将不胜感激。


Dockerfile

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()调用上。对该函数的每次调用只能包含一个include,但允许对该函数进行多次调用。

工作的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 > 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 () 

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...