Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Uso de Bindgen

La herramienta bindgen puede generar automáticamente enlaces desde un archivo de encabezado de C.

En primer lugar, crea una biblioteca de C pequeña:

interoperability/bindgen/libbirthday.h:

typedef struct card {
  const char* name;
  int years;
} card;

void print_card(const card* card);

interoperability/bindgen/libbirthday.c:

#include <stdio.h>
#include "libbirthday.h"

void print_card(const card* card) {
  printf("+--------------\n");
  printf("| ¡Feliz cumpleaños, %s!\n", card->name);
  printf("| ¡Enhorabuena por cumplir %i años!\n", card->years);
  printf("+--------------\n");
}

Añade lo siguiente a tu archivo Android.bp:

interoperability/bindgen/Android.bp:

cc_library {
    name: "libbirthday",
    srcs: ["libbirthday.c"],
}

Crea un archivo de encabezado de envoltorio para la biblioteca (no es estrictamente necesario en este ejemplo):

interoperability/bindgen/libbirthday_wrapper.h:

#include "libbirthday.h"

Ahora puedes generar automáticamente los enlaces:

interoperability/bindgen/Android.bp:

rust_bindgen {
    name: "libbirthday_bindgen",
    crate_name: "birthday_bindgen",
    wrapper_src: "libbirthday_wrapper.h",
    source_stem: "bindings",
    static_libs: ["libbirthday"],
}

Por último, podemos utilizar los enlaces de nuestro programa de Rust:

interoperability/bindgen/Android.bp:

rust_binary {
    name: "print_birthday_card",
    srcs: ["main.rs"],
    rustlibs: ["libbirthday_bindgen"],
}

interoperability/bindgen/main.rs:

//! Demo de Bindgen.

use birthday_bindgen::{card, print_card};

fn main() {
    let name = std::ffi::CString::new("Peter").unwrap();
    let card = card { name: name.as_ptr(), years: 42 };
    // SAFETY: The pointer we pass is valid because it came from a Rust
    // reference, and the `name` it contains refers to `name` above which also
    // remains valid. `print_card` doesn't store either pointer to use later
    // after it returns.
    unsafe {
        print_card(&card as *const card);
    }
}

Compila, inserta y ejecuta el binario en tu dispositivo:

m print_birthday_card
adb push "$ANDROID_PRODUCT_OUT/system/bin/print_birthday_card" /data/local/tmp
adb shell /data/local/tmp/print_birthday_card

Por último, podemos ejecutar pruebas generadas automáticamente para comprobar que los enlaces funcionan:

interoperability/bindgen/Android.bp:

rust_test {
    name: "libbirthday_bindgen_test",
    srcs: [":libbirthday_bindgen"],
    crate_name: "libbirthday_bindgen_test",
    test_suites: ["general-tests"],
    auto_gen_config: true,
    clippy_lints: "ninguno", // Archivo generado, se omite la ejecución de lint
    lints: "ninguno",
}
atest libbirthday_bindgen_test