nuttx-apps/examples/rust/hello/src/lib.rs
Huang Qi f7e7453807 examples: New app to build Rust with Cargo
Build Rust applictions with cargo is the most commn way,
and it's more easy to cooporate with Rust ecosystem.

This example shows how to use cargo to build a simple hello world
application.

And please notice that you need to install nighly version of rustc
to support this feature, any version after https://github.com/rust-lang/rust/pull/127755
is merged, can use NuttX as cargo target directly.

Build
-----

To build hello_rust_cargo application, you can use any target that based
on RISCV32IMAC, for example:
```
cmake -B build -DBOARD_CONFIG=rv-virt:nsh -GNinja .
```

And disable ARCH_FPU in menuconfig, since the hard coded target triple
in this demo is `riscv32imac`.

Signed-off-by: Huang Qi <huangqi3@xiaomi.com>
2025-01-10 22:25:13 +08:00

56 lines
1.2 KiB
Rust

extern crate serde;
extern crate serde_json;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct Person {
name: String,
age: u8,
}
// Function hello_rust_cargo without manglng
#[no_mangle]
pub extern "C" fn hello_rust_cargo_main() {
// Print hello world to stdout
let john = Person {
name: "John".to_string(),
age: 30,
};
let json_str = serde_json::to_string(&john).unwrap();
println!("{}", json_str);
let jane = Person {
name: "Jane".to_string(),
age: 25,
};
let json_str_jane = serde_json::to_string(&jane).unwrap();
println!("{}", json_str_jane);
let json_data = r#"
{
"name": "Alice",
"age": 28
}"#;
let alice: Person = serde_json::from_str(json_data).unwrap();
println!("Deserialized: {} is {} years old", alice.name, alice.age);
let pretty_json_str = serde_json::to_string_pretty(&alice).unwrap();
println!("Pretty JSON:\n{}", pretty_json_str);
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
println!("Hello world from tokio!");
});
loop {
// Do nothing
}
}