Can we assign a value to a given memory location?

后端 未结 7 2139
自闭症患者
自闭症患者 2021-02-05 23:07

I want to assign some value (say 2345) to a memory location(say 0X12AED567). Can this be done?

In other words, how can I implement the following function?



        
相关标签:
7条回答
  • 2021-02-06 00:01

    You've indicated, that the address is a physical address, and that your code is running in a process.

    So if you're

    1. in kind of high level operating system, e.g. Linux, you'd have to get a mapping into the physical address space. In Linux, /dev/mem does that for you.

    2. within the kernel or without operating system and with a MMU, you have to translate the physical address into a virtual address. In the Linux kernel, phys_to_virt() does that for you. In the kernel, I assume, this address is always mapped.

    3. within the kernel or without operating system and without MMU, you write directly to that address. There's no mapping to consider at all.

    Now, you have a valid mapping or the physical address itself, that you pass to your function.

    void AssignValToPointer(uint32_t pointer, int value)
    {
        * ((volatile int *) pointer) = value;
    }
    

    You might want to add the volatile keyword as the compiler might optimize the write-operation away if you do not read from that location afterwards (likely case when writing to a register of a memory-mapped hardware).

    You might also want to use the uintptr_t data type instead of uint32_t for the pointer.

    0 讨论(0)
提交回复
热议问题