如何在Rust中写入内存映射地址?

编程入门 行业动态 更新时间:2024-10-22 22:58:04
本文介绍了如何在Rust中写入内存映射地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我试图在Rust中为STM32F1xx做Blinky。 我知道有libs,但是我想为了学习目的而使自己的lib。

我可以访问STM32的寄存器他们在C中的地址如下:

*(uint32_t *)(0x40021000 + 0x018) 0x10的; *(uint32_t *)(0x40011000 + 0x004)| = 0x33; *(uint32_t *)(0x40011000 + 0x004)& =〜0xCC; *(uint32_t *)(0x40011000 + 0x10)| = 0x300; while(1){}

code> RCC_APB2ENR 注册以启用端口C的时钟,配置引脚并启用我的发现的LED。

将它写在Rust中,使const,fns开始写出好的Rusty代码。有没有FFI可以调用C代码?我可以通过 asm!宏来实现这一点。

解决方案

在C您应该在访问硬件寄存器时将您的指针声明为 volatile ,以便编译器完全按照编程方式进行访问。否则可能会重新排序或消除对同一个注册表的重复访问。

Since Rust 1.9(感谢这个 RFC )你可以使用 core :: ptr :: read_volatile 和 core :: ptr :: write_volatile 读写这些内存。

如果你有一个旧版本的Rust,在 volatile_read 和 volatile_store / intrinsics /rel =nofollow noreferrer> core :: intrinsics ,然而它们永久不稳定,因此需要一个夜间版本的Rust来访问它们。

I'm trying to make "Blinky" for STM32F1xx in Rust. I know that there are libs for it, but I want to make my own "lib" for learning purposes.

I can access STM32's "registers" by their addresses like this in C:

*(uint32_t*)(0x40021000 + 0x018) |= 0x10; *(uint32_t*)(0x40011000 + 0x004) |= 0x33; *(uint32_t*)(0x40011000 + 0x004) &= ~0xCC; *(uint32_t*)(0x40011000 + 0x10) |= 0x300; while(1) {}

This writes some bits to the RCC_APB2ENR register to enable clocking of port C, configures pins and enables LEDs on my Discovery.

I need to re-write this it in Rust, to make consts, fns and start writing nice Rusty code. Is it possible in Rust without FFI calling C code? Can I achieve this with the asm! macro?

解决方案

In C you should declare your pointers as volatile when accessing hardware registers, so that the compiler does the accesses exactly as you program them. Otherwise it could reorder them or eliminate duplicate accesses to the same register.

Since Rust 1.9 (thanks to this RFC) you can use core::ptr::read_volatile and core::ptr::write_volatile to read and write to such memory.

If you have an older version of Rust, these are available as volatile_read and volatile_store in core::intrinsics, which however are permanently unstable, and thus require a nightly version of Rust to access them.

更多推荐

如何在Rust中写入内存映射地址?

本文发布于:2023-08-01 04:25:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1265196.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内存   地址   如何在   Rust

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!