using comma separated strings instead of string arrays...

This commit is contained in:
Nathan Eikermann 2021-06-12 13:41:25 +02:00
parent e4f07ffe2f
commit 9d15ec1cae
5 changed files with 54 additions and 21 deletions

View File

@ -10,7 +10,6 @@ build = "build.rs"
[dependencies]
libc = "0.2"
ffi-convert = "0.5"
[build-dependencies]
cbindgen = "0.19.0"

View File

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

View File

@ -3,4 +3,6 @@
#include <stdint.h>
#include <stdlib.h>
void files_exist(const char *const *f, size_t len);
char *files_exist(const char *f);
void free_str(char *s);

View File

@ -1,15 +1,15 @@
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
extern void files_exist(const char *const *f, size_t len);
extern char *files_exist(const char *f);
extern void free_str(char *s);
int main(int argc, char const* argv[])
{
const char *a[2];
a[0] = "Hello";
a[1] = "World!";
files_exist(a, 2);
char *world = "/home/nathan/Downloads/hackerman.jpg,/home/nathan/x.txt";
char *chunk = files_exist(world);
printf("C: %s", chunk);
free_str(chunk);
return 0;
}

View File

@ -1,27 +1,51 @@
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::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 {
pub extern "C" fn files_exist(f: *const c_char) -> *mut c_char {
let files_c_str = unsafe {
assert!(!f.is_null());
CStringArray { data: f, size: len }
CStr::from_ptr(f)
};
println!("{:?}", files.as_rust().unwrap());
std::mem::forget(files);
println!("Rust C Str: {:?}", files_c_str);
let files_r_str = files_c_str.to_str().unwrap();
println!("Rust Str {:?}", files_r_str);
let files: Vec<&str> = files_r_str.split(",").collect();
println!("Rust Vec {:?}", files);
let mut result = String::new();
for file in files {
result.push_str(file);
if file_exists(file) {
result.push_str(" exists!,");
} else {
result.push_str(" does not exist!,");
}
}
let result_c_str = CString::new(result).unwrap();
return result_c_str.into_raw();
}
#[no_mangle]
pub extern "C" fn free_str(s: *mut c_char) {
unsafe {
if s.is_null() {
return;
}
CString::from_raw(s)
};
}
#[cfg(test)]