简体   繁体   English

将指针传递到内存映射的接口

[英]Passing pointer to memory-mapped interface

I have a global pointer to a memory mapped device initialised as follows: 我有一个指向内存映射设备的全局指针,初始化如下:

volatile char *base_address = (char *) 0xa0000000;

During program execution I have a switch statement, and depending on the input the base_address pointer has to be adjusted as you can see below: 在程序执行期间,我有一个switch语句,根据输入,必须调整base_address指针,如下所示:

    switch (input) {
        case 'S': 
        base_address = (char *) 0xa0001000;
        InitDevice();
    break;
        case 'A': 
        base_address = (char *) 0xa0001000;
        InitDevice();
            break

TBH, this looks like a dirty hack to me and it would be probably nicer to pass the base_address to the function InitDevice((char *) 0xa0001000) . TBH,对我来说这似乎是一个肮脏的技巧,将base_address传递给函数InitDevice((char *) 0xa0001000)可能会更好。 Would the latter be the proper way to do that or are there better approaches? 后者是执行此操作的正确方法还是有更好的方法?

Many thanks, Alex 非常感谢,亚历克斯

Yep, explicitly passing a required parameter to a function is always better than passing it via a global variable. 是的,显式地将必需参数传递给函数总是比通过全局变量传递参数更好。

In an embedded environment, you might have to consider that calling a function with a parameter might require the parameter to be pushed onto the stack and popped otherwise (unless the compiler optimizes and passes it in a register). 在嵌入式环境中,您可能必须考虑使用参数调用函数可能需要将参数压入堆栈并以其他方式弹出(除非编译器对其进行优化并将其传递到寄存器中)。 But I wouldn't optimize based on this unless I have established (through measuring) that the speed gain is actually worth polluting the code. 但是除非基于(通过测量)确定速度增益实际上值得污染代码,否则我不会基于此进行优化。
(And since your example is switching over input, which is usually coming at glacial speed compared to stack operations, this shouldn't be a problem here anyway.) (并且由于您的示例正在切换输入,与堆栈操作相比,输入切换通常以很高的速度进行,因此无论如何这都不是问题。)

However, as Lars said in a comment, it would probably be better if those literal addresses were replaced by symbolic constants: 但是,正如Lars在评论中所说,如果将这些文字地址替换为符号常量可能会更好:

volatile char* const A_base_address = (char *) 0xa0001000;
volatile char* const S_base_address = (char *) 0xa0001000;

switch (input) {
case 'S': 
    InitDevice(S_base_address);
    break;
case 'A': 
    InitDevice(A_base_address);
    break;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM