So when writing the Rust code, you used primitive Rust types. I know in the standard library there is the std::ffi C types that are redefined for Rust, but I understand here in the embedded space having the whole std library is overkill or not possible. My question is though, are there circumstances where the Rust types and C types don’t match in the function signature and the function either fails or causes undefined behavior? If so, would you happen to know any methods by which to avoid this behavior? Thanks for the great video!
I agree with your point here. One of the things I forgot to do/mention in the video is the use of the libc crate to use types that directly map to C types. You can also use cbindgen or bindgen to create rust structures from C headers that are a 1:1 match.
There's the repr(C) directive to specify that a Rust type is to be aligned, sized and ordered exactly like a C type. That should be enough to reliably call into C. Note that calling into C is inherently unsafe in Rust terminology, because obviously Rust can't guarantee that it's own promises are kept by C. The C code might for example free memory that Rust owns or holds a reference to, return uninitialized data and so on.
This video only explains the manual way, though, which is quite error prone. If you actually use this in a project, you might want to look at "bindgen" (calling C from Rust) and "cbindgen" (calling Rust from C) to generate the function stubs automatically.
@@m.sierra5258 I really like knowing the manual way first because it uncovers all the dusty corners. Once I understand that I start looking for tools to make it faster.
@@Dygear oh don't get me wrong, I totally understand and respect that :) I just wanted to point out that this is not the way it would be done in an actual project
Maybe to go further, you could create a library target in the CmakeLists file with perhaps a custom build command to build the whole binary all in one go with the use of a single make command.
Did you explain why you have the rust signatures for gpio_put_explicit and sleep_ms with return type i32, even though the actual C functions both return void?
if you want rust and C to work together easier then make it compile to a obj file and link that to C meaning when compiling then no having to link a library just link both obj files
9:33 I'm curious why you're "lying" to the compiler about the return value. Is it for demo purposes, are you unable to omit the return value, or are you unable to specify `-> ()`?
I read a few articles and I think it's fine to write a function returning a unit type (or nothing) when writing an extern function in rust. So pub extern "C" fn test() { println!("Test"); } Should be a valid ffi function. Ps: It doesn't matter if you write an extern block or put it on every function. Also the "C" can be omitted because as far as I know C is the default for extern in rust.
The "edition" key *does not mean* year created. Rust editions are are not released every year, and it defines a set of things you want that may contain breaking changes (such as the standard library). This allows those core components to be updated and have breaking changes without breaking old projects when they update rust, as they still use the old edition. The default edition is always the most recent edition, in this case 2021(however we may be getting edition 2024 later this year)
That's a cool demo, I'm interested in rust but I've never tried it before, it's an interesting use case ! Just une question, you "lied to the compiler" with the return values, why ? Is it like in maths "when it's too complex for the moment, so we're gonna ignore it" ?
Primarily because the functions are voids and Rust doesn’t have a Null value like other languages. Instead of figuring that out I fudged a little bit 😝
It doesn't import the c functions into Rust. The Rust library has the prototype functions, which become fully defined once it's linked with the C code.
He makes it so fast that I’m not sure for whom this video is for. Should I pump my reaction to press a spacebar in time to be able yo see what he typed just before he run “clear screen”?.. I’m not sure. I’ll better read a manual instead
Really cool video! I was left with a couple of doubts, In the video you declare functions that receive/return integers or booleans, which are variables that both C and Rust understand, what if you want to send a Rust reference or C pointer? Or a struct declared on C or Rust? And is it possible to run C code alongside Rust using the embassy framework?
How do you validate that the ‘bool’ on the C side is the same bit-size as the ‘bool’ on the Rust side? Also how do you validate that the ‘int’ on the C side is the same bit-size as the ‘i32’ on the Rust side? IIRC, I remember that it may cause problems, ‘int’ in C may be 32 bits wide but it doesn’t have to, The same thing about the ‘bool’ type variable, Some languages use an 8 bit integer to represent it while others use a 32 bit integer to represent it, How do you validate that the types on both the C and Rust side align with each other? Thanks.
Read up the Rust FFI. Rust provides a c_int type among many others for this reason. Also, note that while int32_t may be available in many C compilers, it is not required by the C standard to exist. I imagine the embedded world may be one of the few places where this actually matters.
std::os::raw::c_int is what you want. I believe the C standard specifies bool will always be one byte and since its the "same" compiler endianness doesn't matter here.
I wish cmake would let you just add rust as a lang for the project, and then your rust and C code 'just work' together like C and C++. I know there are reasons that make this unrealistic but its really the dream for me to be able to seriously mix it all together
in the first part of the video you did `cmake .`, it's better to keep generated files in a build folder so ``` mkdir build cd build cmake .. ``` that way you can (if you want a clean build) just delete the build folder and create a new one, also if your using git you can add `build` to the .gitignore file so that the build files don't get tracked
If you want to compact it down to a single command line, you can do `cmake -B build && cd build`, or, if the build directory name is the last argument of your cmake command `cmake -B build && cd "$_"`
Hey, would you do a video on the SSD1306 display? how to correctly address page in all modes, horizontal, vertical and page addressing mode, To be able set cursor anywhere to want it. the pages/column thing is easy to understand, basically the stuff from page 28 to 32. you're able to send a single one of multiplier bytes, 2 modules in command and 2 modes for data. the order how bytes are send. the datasheet is kinda hard to understand, more people complain about it. i have seen 2 approaches on how people handle the I²C stuff, but only one of them is how it actually works, the other one an indirect and abstract method, but works. i use a original Microchip Fubarino pic32mx and the Arduino IDE, but not using the arduinio library language of what ever it's called, like you would program a pic and manipulate it's registers directly.
Since they both use LLVM, could you link them at the object level and forgo making them as a library? Assuming names and types match up. I think I'm missing something important here...
Does Rust on the pico have working concurrency? Does Rust work with the memory compactor/defragmenter on FreeRTOS? Edit:Seems like there is a rust crate for interfacing with FreeRTOS.
@@tomtravis858 Guess where I pick up my prophetic insights in the first place? You go outside, come back and tell me I am not your holy Prophet Muhammad with this insight.
2nd this, debugging is a bit flaky on the vscode side when going from rust to c through FFI (x64 non-embedded). It steps in but can't inspect any of the C elements without crashing.
I love C++ but I don't think that C++ and C really are competing today. I believe C++ and Rust are languages that are suitable for application software like compilers or system utilities. However for system software I think languages like Odin, V, Zig and most notably Mojo will be contenders to dethrone C in embedded, system and low-level software. Personally I think this language X is better than language Y is a bit of a flawed perspective as all languages have their pros and cons.
The huge usecase here is that you can transition a project to Rust gradually, without having to completely throw away the previous project. In a commercial setting, this is a major point for adopting rust in your project, no manager would agree to a complete rewrite of the product that would stop all progress for a year. Also, there are many libraries (like for example wifi drivers) that only have C versions, and this enables rust development on a microcontroller while the library ecosystem is not there yet. (or ever will be... Companies won't release multiple versions of their wifi drivers, for example the new openthread, in different languages)
@@m.sierra5258 I'd love it if that were actually the case. I personally just can't ever see that realistically happening. A project would just end up being a wrapper of its former self with tons of unsafes and ultimately fail to prove itself. Maybe there are some super niche projects out there where this would be helpful, idk.
No they can't :). Because the compiler can't no the memory state of data that has gone through C... So even if all your Rust code is safe, C taints it.
That's why it's the goal to make small easy to understand wrapper functions in rust double and triple check them and live the rest of the time in the safe rust world. A 100% safe rust World is impossible unless you rewrite all device driver, operating system and bootloader in rust. Much fun with that. It's not too hard to interface with c safely. It's actually pretty beneficial for the language since you have access to this huge world of c library's.
So when writing the Rust code, you used primitive Rust types. I know in the standard library there is the std::ffi C types that are redefined for Rust, but I understand here in the embedded space having the whole std library is overkill or not possible. My question is though, are there circumstances where the Rust types and C types don’t match in the function signature and the function either fails or causes undefined behavior? If so, would you happen to know any methods by which to avoid this behavior?
Thanks for the great video!
I agree with your point here. One of the things I forgot to do/mention in the video is the use of the libc crate to use types that directly map to C types.
You can also use cbindgen or bindgen to create rust structures from C headers that are a 1:1 match.
Ty for asking lol
@@LowLevelTV Also check out the cty crate
Primitive types won’t be a problem. If you want to return a string for example, you’ll have to convert the Rust string to a CStr and then to a pointer
There's the repr(C) directive to specify that a Rust type is to be aligned, sized and ordered exactly like a C type. That should be enough to reliably call into C.
Note that calling into C is inherently unsafe in Rust terminology, because obviously Rust can't guarantee that it's own promises are kept by C. The C code might for example free memory that Rust owns or holds a reference to, return uninitialized data and so on.
This is going to be very useful as I have a C project that I would love to add some Rust code into. Thank you for showing me the way.
Anytime Mark, I gotchu
This video only explains the manual way, though, which is quite error prone. If you actually use this in a project, you might want to look at "bindgen" (calling C from Rust) and "cbindgen" (calling Rust from C) to generate the function stubs automatically.
@@m.sierra5258 I really like knowing the manual way first because it uncovers all the dusty corners. Once I understand that I start looking for tools to make it faster.
@@Dygear oh don't get me wrong, I totally understand and respect that :) I just wanted to point out that this is not the way it would be done in an actual project
I think this feature makes it easier to migrate away from C.
the edition in rust is actually the Rust major version, it basically the year it was released in, but its not the year you made your project in.
1:55 actually 'edition = "2021"' refers to the RUST VERSION. Has nothing to do with the date you made your project
Maybe to go further, you could create a library target in the CmakeLists file with perhaps a custom build command to build the whole binary all in one go with the use of a single make command.
This is extremely cool. Can't pretend to completely understand it, but the ability to use C libraries could be super-useful in future. Thank you!
you can actually pass the '--lib' flag to cargo new to make a library from the start
Important to note that you still need to configure the Cargo.toml as shown in the video, it just creates the lib.rs file for you automatically.
Did you explain why you have the rust signatures for gpio_put_explicit and sleep_ms with return type i32, even though the actual C functions both return void?
the same thing with "bool" in Rust and "int" in C
This is excellent work. Clear, concise, thorough.
Well, that's convenient. I began a project with C-Rust interop a few hours ago.
I just wanted to thank you for your channel, and the wonderful work you do. Specially the rust embedded
This is great, thanks! My current goals include learning C and Rust, so this video is perfect for me.
Your channel is a gold mine.
if you want rust and C to work together easier then make it compile to a obj file and link that to C meaning when compiling then no having to link a library just link both obj files
Rust has just made it into the linux kernel. Proof that these two languages can live in peace
And now, the Windows11 kernel too.
9:33 I'm curious why you're "lying" to the compiler about the return value. Is it for demo purposes, are you unable to omit the return value, or are you unable to specify `-> ()`?
I read a few articles and I think it's fine to write a function returning a unit type (or nothing) when writing an extern function in rust. So
pub extern "C" fn test() {
println!("Test");
}
Should be a valid ffi function.
Ps:
It doesn't matter if you write an extern block or put it on every function. Also the "C" can be omitted because as far as I know C is the default for extern in rust.
Really awesome video!
The "edition" key *does not mean* year created. Rust editions are are not released every year, and it defines a set of things you want that may contain breaking changes (such as the standard library). This allows those core components to be updated and have breaking changes without breaking old projects when they update rust, as they still use the old edition. The default edition is always the most recent edition, in this case 2021(however we may be getting edition 2024 later this year)
That's a cool demo, I'm interested in rust but I've never tried it before, it's an interesting use case !
Just une question, you "lied to the compiler" with the return values, why ?
Is it like in maths "when it's too complex for the moment, so we're gonna ignore it" ?
Primarily because the functions are voids and Rust doesn’t have a Null value like other languages. Instead of figuring that out I fudged a little bit 😝
@@LowLevelTV Does the Rust unit type "()" not work as a C void?
Panik with a k is just panic in german :D
I maybe missed it, but when do you import the c library into rust? Or how does rust know where those two c functions are?
It doesn't import the c functions into Rust. The Rust library has the prototype functions, which become fully defined once it's linked with the C code.
Great video! I am now on my way to Micro Center to buy a Pi Pico!
Have fun!
You are using terminal impressively fast! How did you figure out the shortcuts?
Those are basics. You'll probably find those on the manpage, or the documentation.
He makes it so fast that I’m not sure for whom this video is for. Should I pump my reaction to press a spacebar in time to be able yo see what he typed just before he run “clear screen”?.. I’m not sure. I’ll better read a manual instead
Another great vid 👍
Really cool video! I was left with a couple of doubts,
In the video you declare functions that receive/return integers or booleans, which are variables that both C and Rust understand, what if you want to send a Rust reference or C pointer? Or a struct declared on C or Rust?
And is it possible to run C code alongside Rust using the embassy framework?
To add here, to help with the CMake import of the library, one could use "corrosion-rs/corrosion".
How do you validate that the ‘bool’ on the C side is the same bit-size as the ‘bool’ on the Rust side?
Also how do you validate that the ‘int’ on the C side is the same bit-size as the ‘i32’ on the Rust side?
IIRC, I remember that it may cause problems, ‘int’ in C may be 32 bits wide but it doesn’t have to, The same thing about the ‘bool’ type variable, Some languages use an 8 bit integer to represent it while others use a 32 bit integer to represent it, How do you validate that the types on both the C and Rust side align with each other? Thanks.
don't write the method stubs manually, use "bindgen" (Rust->C) or "cbindgen" (C->Rust) to generate the correct method stubs automatically.
Read up the Rust FFI. Rust provides a c_int type among many others for this reason. Also, note that while int32_t may be available in many C compilers, it is not required by the C standard to exist. I imagine the embedded world may be one of the few places where this actually matters.
std::os::raw::c_int is what you want. I believe the C standard specifies bool will always be one byte and since its the "same" compiler endianness doesn't matter here.
C Never Dies, U Can add C to Rust, But You can't Add Rust to C.
Ok? Seems like an advantage for Rust to support C.
@@tomtravis858 yup, but C never dies 🩶🤍
I wish cmake would let you just add rust as a lang for the project, and then your rust and C code 'just work' together like C and C++. I know there are reasons that make this unrealistic but its really the dream for me to be able to seriously mix it all together
Potentially, Rust & C++ may integrate via their LLVM intermediate reptesenations
Great video!
in the first part of the video you did `cmake .`, it's better to keep generated files in a build folder so
```
mkdir build
cd build
cmake ..
```
that way you can (if you want a clean build) just delete the build folder and create a new one, also if your using git you can add `build` to the .gitignore file so that the build files don't get tracked
If you want to compact it down to a single command line, you can do `cmake -B build && cd build`, or, if the build directory name is the last argument of your cmake command `cmake -B build && cd "$_"`
Can we use only rust without C for embedded development? Or is there a library which handles all of these FFI things?
Hey, would you do a video on the SSD1306 display?
how to correctly address page in all modes, horizontal, vertical and page addressing mode, To be able set cursor anywhere to want it.
the pages/column thing is easy to understand, basically the stuff from page 28 to 32.
you're able to send a single one of multiplier bytes, 2 modules in command and 2 modes for data.
the order how bytes are send.
the datasheet is kinda hard to understand, more people complain about it.
i have seen 2 approaches on how people handle the I²C stuff, but only one of them is how it actually works, the other one an indirect and abstract method, but works.
i use a original Microchip Fubarino pic32mx and the Arduino IDE, but not using the arduinio library language of what ever it's called, like you would program a pic and manipulate it's registers directly.
My challenge is managing interrupts between two cores where one runs C and the other runs Rust.
Is it possible to have this the other way round? I.e. have the Rust as the library and not the C.
Since they both use LLVM, could you link them at the object level and forgo making them as a library? Assuming names and types match up. I think I'm missing something important here...
It’s a static library so it’s still happening compile time at the object level. I think you’re right, could make this happen at the IR level in LLVM
@@LowLevelTV What would have the added benefit of cross language optimizations.
This would also work with C++, right?
Does Rust on the pico have working concurrency? Does Rust work with the memory compactor/defragmenter on FreeRTOS?
Edit:Seems like there is a rust crate for interfacing with FreeRTOS.
Rust and Soylent Green are our future!
go outside please!
@@tomtravis858 Guess where I pick up my prophetic insights in the first place? You go outside, come back and tell me I am not your holy Prophet Muhammad with this insight.
y do you use sublime instead of nvim?
Any languages can coexist peacefully. It's the people using them can't.
Can we write C to the Pico from Nano?
Please as next step show us debugging this code.
2nd this, debugging is a bit flaky on the vscode side when going from rust to c through FFI (x64 non-embedded). It steps in but can't inspect any of the C elements without crashing.
I love C++ but I don't think that C++ and C really are competing today. I believe C++ and Rust are languages that are suitable for application software like compilers or system utilities. However for system software I think languages like Odin, V, Zig and most notably Mojo will be contenders to dethrone C in embedded, system and low-level software. Personally I think this language X is better than language Y is a bit of a flawed perspective as all languages have their pros and cons.
What is this war?
the edition is the rust's edition, not the project's edition
Its not really obvious
2021 is the version of rust release
edition has nothing to do with your project its the version of rust you run on
Neat
Yeah but then there is no point in using rust. It's still cool knowledge to have I guess but it does defeat the point of using rust.
The huge usecase here is that you can transition a project to Rust gradually, without having to completely throw away the previous project. In a commercial setting, this is a major point for adopting rust in your project, no manager would agree to a complete rewrite of the product that would stop all progress for a year.
Also, there are many libraries (like for example wifi drivers) that only have C versions, and this enables rust development on a microcontroller while the library ecosystem is not there yet. (or ever will be... Companies won't release multiple versions of their wifi drivers, for example the new openthread, in different languages)
@@m.sierra5258 I'd love it if that were actually the case. I personally just can't ever see that realistically happening. A project would just end up being a wrapper of its former self with tons of unsafes and ultimately fail to prove itself. Maybe there are some super niche projects out there where this would be helpful, idk.
yoo finally
Crust
You're writing rust as a C programmer, how dear you?:D
Cope
C+Rust = CRust
CRust.
This was hard to follow, too many aspects went unexplained.
:O
No they can't :). Because the compiler can't no the memory state of data that has gone through C... So even if all your Rust code is safe, C taints it.
That's why it's the goal to make small easy to understand wrapper functions in rust double and triple check them and live the rest of the time in the safe rust world. A 100% safe rust World is impossible unless you rewrite all device driver, operating system and bootloader in rust. Much fun with that. It's not too hard to interface with c safely. It's actually pretty beneficial for the language since you have access to this huge world of c library's.