如何在Rust中写入内存映射地址? [英] How do I write to a memory-mapped address in Rust?

查看:433
本文介绍了如何在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中写入内存映射地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆