feature: Add helloName function to greet with a name

This commit is contained in:
Florian Briand 2024-07-04 22:56:52 +02:00
parent 5645f6ab71
commit 7a22503bac
Signed by: florian_briand
GPG Key ID: CC981B9E6B98E70B
5 changed files with 22 additions and 2 deletions

Binary file not shown.

Binary file not shown.

View File

@ -1,11 +1,13 @@
extern crate libc;
use libc::{ c_char, c_int, c_void, size_t };
use std::ffi::CStr;
use std::ffi::{ CStr, CString };
use std::ptr;
extern {
#[link(name = "p4pillondebuglib")]
extern "C" {
fn hello() -> *const c_char;
fn helloName(name: *const c_char) -> *const c_char;
fn helloPtr(result: *mut c_char);
fn helloPtrPtr(result: *mut *mut c_char, size: *mut size_t);
fn helloVoidPtrPtr(result: *mut *mut c_void, size: *mut size_t);
@ -22,6 +24,15 @@ fn main() {
println!("{} from C", r_str);
}
let name = CString::new("John").expect("CString::new failed");
unsafe {
let c_str = helloName(name.as_ptr());
let r_str = CStr::from_ptr(c_str).to_str().expect("Conversion failed");
println!("{} from C with name", r_str);
libc::free(c_str as *mut c_void);
}
let mut buffer: [c_char; 50] = [0; 50];
unsafe {
helloPtr(buffer.as_mut_ptr());

View File

@ -7,6 +7,14 @@ char* hello() {
return "Hello, World!";
}
char* helloName(const char *name) {
char *result = (char *)malloc(strlen(name) + 9);
if (result) {
sprintf(result, "Hello, %s!", name);
}
return result;
}
void helloPtr(char *result) {
sprintf(result, "Hello, World!");
}

View File

@ -4,6 +4,7 @@
#include <stddef.h>
char* hello();
char* helloName(const char *name);
void helloPtr(char *result);
void helloPtrPtr(char **result, size_t *size);
void helloVoidPtrPtr(void **result, size_t *size);