feature: Add helloName function to greet with a name
This commit is contained in:
parent
5645f6ab71
commit
7a22503bac
Binary file not shown.
Binary file not shown.
15
src/main.rs
15
src/main.rs
@ -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());
|
||||
|
@ -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!");
|
||||
}
|
||||
|
@ -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);
|
||||
|
Loading…
Reference in New Issue
Block a user