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

Поділитися
Вставка
  • Опубліковано 16 січ 2025

КОМЕНТАРІ • 96

  • @ShadowFluux
    @ShadowFluux 2 роки тому +92

    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!

    • @LowLevelTV
      @LowLevelTV  2 роки тому +61

      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 роки тому +2

      Ty for asking lol

    • @ArnabAnimeshDas
      @ArnabAnimeshDas 2 роки тому +2

      @@LowLevelTV 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 роки тому +7

      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 роки тому +128

    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.

    • @LowLevelTV
      @LowLevelTV  2 роки тому +18

      Anytime Mark, I gotchu

    • @m.sierra5258
      @m.sierra5258 2 роки тому +11

      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 роки тому +19

      @@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 роки тому +8

      @@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 8 місяців тому

      I think this feature makes it easier to migrate away from C.

  • @wChris_
    @wChris_ 2 роки тому +53

    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.

  • @diogob003
    @diogob003 Рік тому +5

    1:55 actually 'edition = "2021"' refers to the RUST VERSION. Has nothing to do with the date you made your project

  • @thetos
    @thetos 2 роки тому +7

    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.

  • @chairmakerPete
    @chairmakerPete 2 роки тому +4

    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!

  • @wChris_
    @wChris_ 2 роки тому +40

    you can actually pass the '--lib' flag to cargo new to make a library from the start

    • @gagagero
      @gagagero 2 роки тому +7

      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.

  • @meatmanek
    @meatmanek 2 роки тому +19

    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 Рік тому +1

      the same thing with "bool" in Rust and "int" in C

  • @jaredkomoroski
    @jaredkomoroski 2 роки тому +2

    This is excellent work. Clear, concise, thorough.

  • @gagagero
    @gagagero 2 роки тому +3

    Well, that's convenient. I began a project with C-Rust interop a few hours ago.

  • @zeroows
    @zeroows Рік тому +1

    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.

  • @AtmoPierce
    @AtmoPierce 2 роки тому +1

    Your channel is a gold mine.

  • @ltecheroffical
    @ltecheroffical 7 місяців тому

    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

  • @conor-smith572
    @conor-smith572 2 роки тому +1

    Rust has just made it into the linux kernel. Proof that these two languages can live in peace

  • @raffimolero64
    @raffimolero64 2 роки тому +1

    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 роки тому +1

      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.

  • @sydpao2224
    @sydpao2224 Рік тому

    Really awesome video!

  • @tryoxiss
    @tryoxiss 10 місяців тому

    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)

  • @willexco2001
    @willexco2001 2 роки тому +3

    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" ?

    • @LowLevelTV
      @LowLevelTV  2 роки тому +3

      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 роки тому +4

      @@LowLevelTV Does the Rust unit type "()" not work as a C void?

  • @jogewe
    @jogewe 2 роки тому +5

    Panik with a k is just panic in german :D

  • @hansdampf2284
    @hansdampf2284 2 роки тому +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 2 роки тому

      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.

  • @CT-cx8yi
    @CT-cx8yi 2 роки тому +1

    Great video! I am now on my way to Micro Center to buy a Pi Pico!

  • @no_name4837
    @no_name4837 2 роки тому +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 11 місяців тому

      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

  • @Lorestel
    @Lorestel 2 роки тому

    Another great vid 👍

  • @Juan-um7du
    @Juan-um7du Рік тому

    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?

  • @aliancemd
    @aliancemd 2 роки тому +1

    To add here, to help with the CMake import of the library, one could use "corrosion-rs/corrosion".

  • @astroid-ws4py
    @astroid-ws4py 2 роки тому +10

    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 роки тому +5

      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 роки тому +4

      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 2 роки тому

      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.

  • @QuickBitMastery
    @QuickBitMastery Рік тому +1

    C Never Dies, U Can add C to Rust, But You can't Add Rust to C.

    • @tomtravis858
      @tomtravis858 Рік тому +2

      Ok? Seems like an advantage for Rust to support C.

    • @QuickBitMastery
      @QuickBitMastery Рік тому

      @@tomtravis858 yup, but C never dies 🩶🤍

  • @disabledmallis
    @disabledmallis 2 роки тому +4

    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

  • @LeandroCoutinho
    @LeandroCoutinho 2 роки тому

    Great video!

  • @amrshatnawi
    @amrshatnawi 2 роки тому +1

    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 "$_"`

  • @InMemoryOfNeo
    @InMemoryOfNeo 5 місяців тому

    Can we use only rust without C for embedded development? Or is there a library which handles all of these FFI things?

  • @AnalogDude_
    @AnalogDude_ 2 роки тому

    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.

  • @kippie80
    @kippie80 Рік тому

    My challenge is managing interrupts between two cores where one runs C and the other runs Rust.

  • @S0me0ne_S0meWhere_SaysHi
    @S0me0ne_S0meWhere_SaysHi Рік тому

    Is it possible to have this the other way round? I.e. have the Rust as the library and not the C.

  • @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...

    • @LowLevelTV
      @LowLevelTV  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 роки тому

      @@LowLevelTV What would have the added benefit of cross language optimizations.

  • @tristanmisja
    @tristanmisja 2 роки тому

    This would also work with C++, right?

  • @Kuratius
    @Kuratius 2 роки тому

    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.

  • @rusurveillancetaskforce
    @rusurveillancetaskforce 2 роки тому

    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.

  • @fntr
    @fntr Рік тому

    y do you use sublime instead of nvim?

  • @realsong-fake
    @realsong-fake 2 роки тому +1

    Any languages can coexist peacefully. It's the people using them can't.

  • @eljuano28
    @eljuano28 2 роки тому

    Can we write C to the Pico from Nano?

  • @michadunajski4366
    @michadunajski4366 2 роки тому +2

    Please as next step show us debugging this code.

    • @ic3man5
      @ic3man5 2 роки тому

      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.

  • @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.

  • @AceofSpades5757
    @AceofSpades5757 2 роки тому +1

    What is this war?

  • @coffee-is-power
    @coffee-is-power 2 роки тому

    the edition is the rust's edition, not the project's edition
    Its not really obvious

  • @herrxerex8484
    @herrxerex8484 2 роки тому +1

    2021 is the version of rust release

  • @samuelfischer3764
    @samuelfischer3764 Рік тому

    edition has nothing to do with your project its the version of rust you run on

  • @KramerEspinoza
    @KramerEspinoza 2 роки тому

    Neat

  • @penguin1714
    @penguin1714 2 роки тому +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 роки тому +6

      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 роки тому +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.

  • @plexx731
    @plexx731 2 роки тому +2

    yoo finally

  • @wil3630
    @wil3630 2 роки тому

    Crust

  • @coldsir5406
    @coldsir5406 2 роки тому

    You're writing rust as a C programmer, how dear you?:D

  • @larrythehedgehog
    @larrythehedgehog 2 роки тому +1

    C+Rust = CRust

  • @jxkc.3941
    @jxkc.3941 2 роки тому

    CRust.

  • @gustawbobowski1333
    @gustawbobowski1333 2 роки тому

    This was hard to follow, too many aspects went unexplained.

  • @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 роки тому +3

      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.