No video

Don't Worry, C and Rust Can FINALLY Coexist (Here's How) | Embedded Rust and C on the RP2040 Pi Pico

  Рет қаралды 50,655

Low Level Learning

Low Level Learning

Күн бұрын

Пікірлер: 96
@ShadowFluux
@ShadowFluux 2 жыл бұрын
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!
@LowLevelLearning
@LowLevelLearning 2 жыл бұрын
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.
@typeer
@typeer 2 жыл бұрын
Ty for asking lol
@ArnabAnimeshDas
@ArnabAnimeshDas 2 жыл бұрын
@@LowLevelLearning Also check out the cty crate
@jomy10-games
@jomy10-games 2 жыл бұрын
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
@swapode
@swapode 2 жыл бұрын
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.
@Dygear
@Dygear 2 жыл бұрын
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.
@LowLevelLearning
@LowLevelLearning 2 жыл бұрын
Anytime Mark, I gotchu
@m.sierra5258
@m.sierra5258 2 жыл бұрын
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.
@Dygear
@Dygear 2 жыл бұрын
@@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.
@m.sierra5258
@m.sierra5258 2 жыл бұрын
@@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
@Barnardrab
@Barnardrab 3 ай бұрын
I think this feature makes it easier to migrate away from C.
@wChris_
@wChris_ 2 жыл бұрын
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.
@wChris_
@wChris_ 2 жыл бұрын
you can actually pass the '--lib' flag to cargo new to make a library from the start
@gagagero
@gagagero 2 жыл бұрын
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.
@thetos
@thetos 2 жыл бұрын
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.
@diogob003
@diogob003 Жыл бұрын
1:55 actually 'edition = "2021"' refers to the RUST VERSION. Has nothing to do with the date you made your project
@chairmakerPete
@chairmakerPete 2 жыл бұрын
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!
@meatmanek
@meatmanek 2 жыл бұрын
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?
@dj-maxus
@dj-maxus Жыл бұрын
the same thing with "bool" in Rust and "int" in C
@disabledmallis
@disabledmallis 2 жыл бұрын
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
@dj-maxus
@dj-maxus Жыл бұрын
Potentially, Rust & C++ may integrate via their LLVM intermediate reptesenations
@ltecheroffical
@ltecheroffical 3 ай бұрын
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
@jaredkomoroski
@jaredkomoroski 2 жыл бұрын
This is excellent work. Clear, concise, thorough.
@gagagero
@gagagero 2 жыл бұрын
Well, that's convenient. I began a project with C-Rust interop a few hours ago.
@tryoxiss
@tryoxiss 5 ай бұрын
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)
@zeroows
@zeroows Жыл бұрын
I just wanted to thank you for your channel, and the wonderful work you do. Specially the rust embedded
@rebelmachine88
@rebelmachine88 2 жыл бұрын
This is great, thanks! My current goals include learning C and Rust, so this video is perfect for me.
@bigmeechmane
@bigmeechmane 2 жыл бұрын
Your channel is a gold mine.
@conor-smith572
@conor-smith572 Жыл бұрын
Rust has just made it into the linux kernel. Proof that these two languages can live in peace
@notdumbrella6399
@notdumbrella6399 Жыл бұрын
And now, the Windows11 kernel too.
@jogewe
@jogewe 2 жыл бұрын
Panik with a k is just panic in german :D
@CT-cx8yi
@CT-cx8yi 2 жыл бұрын
Great video! I am now on my way to Micro Center to buy a Pi Pico!
@LowLevelLearning
@LowLevelLearning 2 жыл бұрын
Have fun!
@amrshatnawi
@amrshatnawi 2 жыл бұрын
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
@thetos
@thetos 2 жыл бұрын
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 "$_"`
@willexco2001
@willexco2001 2 жыл бұрын
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" ?
@LowLevelLearning
@LowLevelLearning 2 жыл бұрын
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 😝
@kulasko5481
@kulasko5481 2 жыл бұрын
@@LowLevelLearning Does the Rust unit type "()" not work as a C void?
@aliancemd
@aliancemd 2 жыл бұрын
To add here, to help with the CMake import of the library, one could use "corrosion-rs/corrosion".
@astroid-ws4py
@astroid-ws4py 2 жыл бұрын
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.
@m.sierra5258
@m.sierra5258 2 жыл бұрын
don't write the method stubs manually, use "bindgen" (Rust->C) or "cbindgen" (C->Rust) to generate the correct method stubs automatically.
@wile9763
@wile9763 2 жыл бұрын
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.
@ic3man5
@ic3man5 Жыл бұрын
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.
@hansdampf2284
@hansdampf2284 2 жыл бұрын
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?
@tristanmisja
@tristanmisja Жыл бұрын
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.
@sydpao2224
@sydpao2224 Жыл бұрын
Really awesome video!
@no_name4837
@no_name4837 2 жыл бұрын
You are using terminal impressively fast! How did you figure out the shortcuts?
@notdumbrella6399
@notdumbrella6399 Жыл бұрын
Those are basics. You'll probably find those on the manpage, or the documentation.
@sc0or
@sc0or 6 ай бұрын
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
@Juan-um7du
@Juan-um7du 7 ай бұрын
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?
@InMemoryOfNeo
@InMemoryOfNeo 27 күн бұрын
Can we use only rust without C for embedded development? Or is there a library which handles all of these FFI things?
@Lorestel
@Lorestel 2 жыл бұрын
Another great vid 👍
@raffimolero64
@raffimolero64 2 жыл бұрын
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 `-> ()`?
@redcrafterlppa303
@redcrafterlppa303 2 жыл бұрын
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.
@LeandroCoutinho
@LeandroCoutinho 2 жыл бұрын
Great video!
@kippie80
@kippie80 Жыл бұрын
My challenge is managing interrupts between two cores where one runs C and the other runs Rust.
@torarinvik4920
@torarinvik4920 Жыл бұрын
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.
@everestshadow
@everestshadow 2 жыл бұрын
Any languages can coexist peacefully. It's the people using them can't.
@fntr
@fntr Жыл бұрын
y do you use sublime instead of nvim?
@Kuratius
@Kuratius Жыл бұрын
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.
@AnalogDude_
@AnalogDude_ Жыл бұрын
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.
@QuickBitMastery
@QuickBitMastery Жыл бұрын
C Never Dies, U Can add C to Rust, But You can't Add Rust to C.
@tomtravis858
@tomtravis858 Жыл бұрын
Ok? Seems like an advantage for Rust to support C.
@QuickBitMastery
@QuickBitMastery Жыл бұрын
@@tomtravis858 yup, but C never dies 🩶🤍
@plexx731
@plexx731 2 жыл бұрын
yoo finally
@barryh9653
@barryh9653 Жыл бұрын
Is it possible to have this the other way round? I.e. have the Rust as the library and not the C.
@michadunajski4366
@michadunajski4366 2 жыл бұрын
Please as next step show us debugging this code.
@ic3man5
@ic3man5 Жыл бұрын
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.
@rusurveillancetaskforce
@rusurveillancetaskforce Жыл бұрын
Rust and Soylent Green are our future!
@tomtravis858
@tomtravis858 Жыл бұрын
go outside please!
@rusurveillancetaskforce
@rusurveillancetaskforce Жыл бұрын
@@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.
@ttamttam1522
@ttamttam1522 2 жыл бұрын
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...
@LowLevelLearning
@LowLevelLearning 2 жыл бұрын
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
@remrevo3944
@remrevo3944 2 жыл бұрын
@@LowLevelLearning What would have the added benefit of cross language optimizations.
@penguin1714
@penguin1714 2 жыл бұрын
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.
@m.sierra5258
@m.sierra5258 2 жыл бұрын
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)
@penguin1714
@penguin1714 2 жыл бұрын
@@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.
@tristanmisja
@tristanmisja Жыл бұрын
This would also work with C++, right?
@eljuano28
@eljuano28 2 жыл бұрын
Can we write C to the Pico from Nano?
@herrxerex8484
@herrxerex8484 2 жыл бұрын
2021 is the version of rust release
@coffee-is-power
@coffee-is-power 2 жыл бұрын
the edition is the rust's edition, not the project's edition Its not really obvious
@samuelfischer3764
@samuelfischer3764 Жыл бұрын
edition has nothing to do with your project its the version of rust you run on
@AceofSpades5757
@AceofSpades5757 2 жыл бұрын
What is this war?
@larrythehedgehog
@larrythehedgehog 2 жыл бұрын
C+Rust = CRust
@wil3630
@wil3630 2 жыл бұрын
Crust
@KramerEspinoza
@KramerEspinoza 2 жыл бұрын
Neat
@gustawbobowski1333
@gustawbobowski1333 2 жыл бұрын
This was hard to follow, too many aspects went unexplained.
@jxkc.3941
@jxkc.3941 2 жыл бұрын
CRust.
@coldsir5406
@coldsir5406 2 жыл бұрын
You're writing rust as a C programmer, how dear you?:D
@notdumbrella6399
@notdumbrella6399 Жыл бұрын
Cope
@kalucky0
@kalucky0 2 жыл бұрын
:O
@alexdubois6585
@alexdubois6585 2 жыл бұрын
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.
@redcrafterlppa303
@redcrafterlppa303 2 жыл бұрын
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.
rust runs on EVERYTHING (no operating system, just Rust)
18:10
Low Level Learning
Рет қаралды 354 М.
managed to catch #tiktok
00:16
Анастасия Тарасова
Рет қаралды 47 МЛН
Incredible Dog Rescues Kittens from Bus - Inspiring Story #shorts
00:18
Fabiosa Best Lifehacks
Рет қаралды 27 МЛН
SPILLED CHOCKY MILK PRANK ON BROTHER 😂 #shorts
00:12
Savage Vlogs
Рет қаралды 49 МЛН
microsoft doubles down on recording your screen
10:00
Low Level Learning
Рет қаралды 101 М.
why do header files even exist?
10:53
Low Level Learning
Рет қаралды 395 М.
Val - The Rust Killer | Prime Reacts
16:54
ThePrimeTime
Рет қаралды 94 М.
Moving from C to Rust for embedded software development
10:06
The Rusty Bits
Рет қаралды 81 М.
Rust: When C Code Isn't Enough
8:26
CodeAhead
Рет қаралды 159 М.
rust runs on EVERYTHING (no operating system, just Rust)
14:29
Low Level Learning
Рет қаралды 211 М.
The Raspberry Pi Pico WAS Overrated! But that changed!
10:18
GreatScott!
Рет қаралды 606 М.
Why do developers hate Rust?
8:20
Let's Get Rusty
Рет қаралды 113 М.
RUST Enums ARE Better
5:49
ThePrimeagen
Рет қаралды 141 М.
why rust libraries may never exist.
7:26
Low Level Learning
Рет қаралды 244 М.