This commit is contained in:
stickynotememo
2025-12-19 17:07:07 +11:00
parent 9d6829199f
commit 806ff9ce43
7 changed files with 61 additions and 7 deletions
+1
View File
@@ -0,0 +1 @@
/target
+25
View File
@@ -0,0 +1,25 @@
use std::ffi::CStr;
use std::ffi::c_char;
#[cfg(target_family = "unix")]
extern "C" {
fn _2_c_func() -> *const c_char;
}
fn main() -> Result<(), String> {
let raw_string_pointer: *const c_char = unsafe { _2_c_func() };
if raw_string_pointer.is_null() {
return Err(String::from("pointer is null"));
};
let c_string = unsafe { CStr::from_ptr(raw_string_pointer) }; // SAFETY: we are assuming the
// string is null terminated since we created it ourselves in a previous program. However, if
// it is not, it is UB.
let Some(string) = c_string.to_str() else {
return Err(String::from("string should be null terminated"))
};
println!("{}", string);
Ok(())
}
+1 -1
View File
@@ -4,7 +4,7 @@
# -L target -l 2_c # -L target -l 2_c
2_c: 1_assembly 2_c: 1_assembly
gcc -Wall -Wpedantic -Werror src/2_c.c -c -o target/2_c.o gcc -Wall -Wpedantic -Werror src/2_c.c -c -fPIC -o target/2_c.o
# ar rcs target/lib2_c.a target/2_c.o # ar rcs target/lib2_c.a target/2_c.o
1_assembly: 1_assembly:
+2
View File
@@ -0,0 +1,2 @@
# Chinese Whispers
A project to pass a string between as many languages as I know.
+2 -2
View File
@@ -10,9 +10,9 @@ section .text
; syscall ; invoke operating system to exit ; syscall ; invoke operating system to exit
_1_assembly_func: _1_assembly_func:
mov rax, message lea rax, [rel message]
ret ret
section .data section .data
message: db "Hello from Assembly.", 21 ; note the newline at the end; Define variables in the data section message: db "Hello from Assembly.", 0xA, 23 ; note the newline at the end; Define variables in the data section
+3 -4
View File
@@ -5,10 +5,9 @@ extern char* _1_assembly_func(void);
char* _2_c_func() { char* _2_c_func() {
char * asm_buf = _1_assembly_func(); char * asm_buf = _1_assembly_func();
char * buf = malloc(22 + 16); char * buf = malloc(24 + 16);
memcpy(buf, asm_buf, 22); memcpy(buf, asm_buf, 24);
strcat(buf, "\nHello from C."); strcat(buf, "Hello from C.\n");
printf("%s", buf);
return buf; return buf;
} }
+27
View File
@@ -0,0 +1,27 @@
use std::ffi::CStr;
use std::ffi::c_char;
#[cfg(target_family = "unix")]
extern "C" {
fn _2_c_func() -> *const c_char;
}
fn main() -> Result<(), String> {
let raw_string_pointer: *const c_char = unsafe { _2_c_func() };
if raw_string_pointer.is_null() {
return Err(String::from("pointer is null"));
};
let c_string = unsafe { CStr::from_ptr(raw_string_pointer) }; // SAFETY: we are assuming the
// string is null terminated since we created it ourselves in a previous program. However, if
// it is not, it is UB.
let Ok(string) = c_string.to_str() else {
return Err(String::from("string should be null terminated"))
};
let mut string = String::from(string);
string.push_str("Hello from Rust.");
println!("{}", string);
Ok(())
}