examples/rust: Show command arguments in hello_rust_cargo

Print each argument passed from nsh with its index, and report when
the example is running on the simulator target. This makes the Rust
example demonstrate both C argv handling and target-specific output.

Signed-off-by: Shoji Tokunaga <toku@mac.​com>
This commit is contained in:
Shoji Tokunaga 2026-06-18 23:53:58 +09:00 committed by Alan C. Assis
parent d1202bd501
commit 8d6c495365

View file

@ -1,7 +1,7 @@
extern crate serde;
extern crate serde_json;
use core::ffi::{c_char, c_int};
use core::ffi::{c_char, c_int, CStr};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
@ -10,10 +10,29 @@ struct Person {
age: u8,
}
// Function hello_rust_cargo without manglng
fn print_args(argc: c_int, argv: *mut *mut c_char) {
if argv.is_null() {
return;
}
for i in 1..argc {
let arg = unsafe { *argv.add(i as usize) };
if arg.is_null() {
continue;
}
let arg = unsafe { CStr::from_ptr(arg) }.to_string_lossy();
println!("{}: {}", i, arg);
}
}
// Function hello_rust_cargo without mangling
#[no_mangle]
pub extern "C" fn hello_rust_cargo_main(_argc: c_int, _argv: *mut *mut c_char) -> c_int {
// Print hello world to stdout
pub extern "C" fn hello_rust_cargo_main(argc: c_int, argv: *mut *mut c_char) -> c_int {
print_args(argc, argv);
#[cfg(feature = "sim")]
println!("On simulator");
let john = Person {
name: "John".to_string(),
@ -50,12 +69,5 @@ pub extern "C" fn hello_rust_cargo_main(_argc: c_int, _argv: *mut *mut c_char) -
.block_on(async {
println!("Hello world from tokio!");
});
#[cfg(not(feature = "sim"))]
loop {
// Do nothing
}
#[cfg(feature = "sim")]
0
}