we can now read c style string arrays

This commit is contained in:
Nathan Eikermann 2021-06-02 00:45:26 +02:00
parent b1e39cdb75
commit e4f07ffe2f
7 changed files with 77 additions and 2 deletions

1
.gitignore vendored
View File

@ -1,2 +1,3 @@
/target /target
Cargo.lock Cargo.lock
/ctest/test

View File

@ -4,11 +4,16 @@ version = "0.1.0"
authors = ["Nathan Eikermann <tensazangetsu1990@googlemail.com>"] authors = ["Nathan Eikermann <tensazangetsu1990@googlemail.com>"]
description = "A rust library providing various utilities. To be used via FFI" description = "A rust library providing various utilities. To be used via FFI"
edition = "2018" edition = "2018"
#build = "build.rs" build = "build.rs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
libc = "0.2"
ffi-convert = "0.5"
[build-dependencies]
cbindgen = "0.19.0"
[lib] [lib]
crate-type = ["cdylib", "lib"] crate-type = ["cdylib", "lib"]

6
Makefile Normal file
View File

@ -0,0 +1,6 @@
DEBUG=target/debug/libmd_util_rs.so
FILE=ctest/test.c
OUTPUT=ctest/test
test:
gcc -o ${OUTPUT} ${FILE} -Isrc -L. -l:${DEBUG}
./ctest/test

14
build.rs Normal file
View File

@ -0,0 +1,14 @@
extern crate cbindgen;
use std::env;
fn main() {
let crate_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
cbindgen::Builder::new()
.with_crate(crate_dir)
.with_language(cbindgen::Language::C)
.generate()
.expect("Unable to generate bindings")
.write_to_file("./ctest/bindings.h");
}

6
ctest/bindings.h Normal file
View File

@ -0,0 +1,6 @@
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
void files_exist(const char *const *f, size_t len);

15
ctest/test.c Normal file
View File

@ -0,0 +1,15 @@
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
extern void files_exist(const char *const *f, size_t len);
int main(int argc, char const* argv[])
{
const char *a[2];
a[0] = "Hello";
a[1] = "World!";
files_exist(a, 2);
return 0;
}

View File

@ -1,7 +1,35 @@
extern crate ffi_convert;
extern crate libc;
use ffi_convert::{AsRust, CReprOf, CStringArray};
use libc::c_char;
use libc::size_t;
//use std::ffi::CStr;
//use std::ffi::CString;
use std::path::Path;
//use std::slice;
fn file_exists(file_path: &str) -> bool {
return Path::new(file_path).is_file();
}
#[no_mangle]
pub extern "C" fn files_exist(f: *const *const c_char, len: size_t) -> () {
let files = unsafe {
assert!(!f.is_null());
CStringArray { data: f, size: len }
};
println!("{:?}", files.as_rust().unwrap());
std::mem::forget(files);
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
#[test] #[test]
fn it_works() { fn it_works() {
assert_eq!(2 + 2, 4); assert_eq!(file_exists("/home/nathan/Downloads/cert.sh"), true);
} }
} }