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

Поделиться
HTML-код
  • Опубликовано: 14 июл 2024
  • FINALLY! Embedded C and Rust can coexist. For the longest time, there had been the great war of Rust vs C. In this video, I teach you how to create a Rust Crate and write C code for the Raspberry Pi Pico RP2040 that allows you to use both in an embedded environment. By creating a static archive library and linking it against your C code, you can compile Rust with your C for them to both run in the same runtime.
    Low Level Merch!: www.linktr.ee/lowlevellearning
    Follow me on Twitter: / lowlevellearni1
    Follow me on Twitch: / lowlevellearning
    Join me on Discord!: / discord
    Follow along with me!: github.com/lowlevellearning/r...
    0:00 Introduction
    1:17 Rust Library Crate
    5:47 Linking Rust + C
    7:43 Adding C to Rust
  • НаукаНаука

Комментарии • 95

  • @ShadowFluux
    @ShadowFluux 2 года назад +85

    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 года назад +56

      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

      @@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 года назад +6

      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 года назад +123

    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 года назад +17

      Anytime Mark, I gotchu

    • @m.sierra5258
      @m.sierra5258 2 года назад +10

      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 года назад +18

      @@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 2 месяца назад

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

  • @wChris_
    @wChris_ 2 года назад +51

    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 года назад +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.

  • @jaredkomoroski
    @jaredkomoroski 2 года назад +2

    This is excellent work. Clear, concise, thorough.

  • @rebelmachine88
    @rebelmachine88 2 года назад

    This is great, thanks! My current goals include learning C and Rust, so this video is perfect for me.

  • @zeroows
    @zeroows Год назад +1

    I just wanted to thank you for your channel, and the wonderful work you do. Specially the rust embedded

  • @chairmakerPete
    @chairmakerPete 2 года назад +3

    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!

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

  • @gagagero
    @gagagero 2 года назад +2

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

  • @sydpao2224
    @sydpao2224 Год назад

    Really awesome video!

  • @Lorestel
    @Lorestel 2 года назад

    Another great vid 👍

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

  • @LeandroCoutinho
    @LeandroCoutinho 2 года назад

    Great video!

  • @bigmeechmane
    @bigmeechmane 2 года назад +1

    Your channel is a gold mine.

  • @CT-cx8yi
    @CT-cx8yi 2 года назад +1

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

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

  • @ltecheroffical
    @ltecheroffical Месяц назад

    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

  • @Juan-um7du
    @Juan-um7du 6 месяцев назад

    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?

  • @conor-smith572
    @conor-smith572 Год назад +1

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

  • @tryoxiss
    @tryoxiss 3 месяца назад

    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)

  • @jogewe
    @jogewe 2 года назад +4

    Panik with a k is just panic in german :D

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

  • @aliancemd
    @aliancemd 2 года назад +1

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

  • @diogob003
    @diogob003 Год назад +3

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

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

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

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

  • @kippie80
    @kippie80 11 месяцев назад

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

  • @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 Год назад

      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.

  • @no_name4837
    @no_name4837 Год назад +2

    You are using terminal impressively fast! How did you figure out the shortcuts?

    • @notdumbrella6399
      @notdumbrella6399 11 месяцев назад

      Those are basics. You'll probably find those on the manpage, or the documentation.

    • @sc0or
      @sc0or 4 месяца назад

      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

  • @plexx731
    @plexx731 2 года назад +2

    yoo finally

  • @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 Год назад

      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.

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

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

  • @barryh9653
    @barryh9653 Год назад

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

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

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

  • @eljuano28
    @eljuano28 2 года назад

    Can we write C to the Pico from Nano?

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

  • @fntr
    @fntr Год назад

    y do you use sublime instead of nvim?

  • @tristanmisja
    @tristanmisja Год назад

    This would also work with C++, right?

  • @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 🩶🤍

  • @torarinvik4920
    @torarinvik4920 11 месяцев назад

    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 года назад +1

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

  • @herrxerex8484
    @herrxerex8484 2 года назад +1

    2021 is the version of rust release

  • @michadunajski4366
    @michadunajski4366 2 года назад +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.

  • @AceofSpades5757
    @AceofSpades5757 2 года назад +1

    What is this war?

  • @wil3630
    @wil3630 2 года назад

    Crust

  • @coldsir5406
    @coldsir5406 2 года назад

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

  • @coffee-is-power
    @coffee-is-power 2 года назад

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

  • @KramerEspinoza
    @KramerEspinoza 2 года назад

    Neat

  • @larrythehedgehog
    @larrythehedgehog Год назад +1

    C+Rust = CRust

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

  • @jxkc.3941
    @jxkc.3941 2 года назад

    CRust.

  • @samuelfischer3764
    @samuelfischer3764 Год назад

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

  • @kalucky0
    @kalucky0 2 года назад

    :O

  • @gustawbobowski1333
    @gustawbobowski1333 2 года назад

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

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