Luciano
Luciano

Reputation: 33

What is (uint32_t*)?

I am new to C. I don't understand how to solve the last two lines of the following code, can you explain it? thank you very much.

pBuffcmd = (uint32_t*)&CmdBuffer[CmdBuffer_Index]; *pBuffcmd = cmd;

#DL_SIZE                  (8*1024L)
#define CMD_FIFO_SIZE     (4*1024L)
#define CMD_SIZE          (4)/

uint32_t CmdBuffer_Index;
volatile uint32_t DlBuffer_Index;

uint8_t  DlBuffer[DL_SIZE];
uint8_t  CmdBuffer[CMD_FIFO_SIZE];

void App_WrCoCmd_Buffer(Gpu_Hal_Context_t *phost,uint32_t cmd)
{
#ifdef  BUFFER_OPTIMIZATION

    uint32_t *pBuffcmd;

    if (CmdBuffer_Index >= CMD_FIFO_SIZE) 
    {
        if (CmdBuffer_Index > 0) {
            NOP;
        }
        CmdBuffer_Index = 0;
    }
    pBuffcmd = (uint32_t*)&CmdBuffer[CmdBuffer_Index];
    *pBuffcmd = cmd;

Upvotes: 1

Views: 1616

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 223274

(uint32_t*) is a cast. A cast is an operator that performs a conversion.

In this code, &CmdBuffer[CmdBuffer_Index] is a pointer to a particular element in CmdBuffer, and the type of that pointer is “pointer to uint8_t”, also written uint8_t *. This cast converts it to a pointer to a uint32_t, also written uint32_t *.

Then *pBuffcmd = cmd; attempts to write the value cmd to the uint32_t pointed to by the converted pointer.

This is bad code. The C standard does not guarantee that converting a uint8_t * to a uint32_t * will work. Even if that does work, the C standard does not guarantee that using a uint32_t reference to write to bytes in an array defined with element type uint8_t will work. It may be this code is designed for a particular C implementation in which that will work, but the desired result could be obtained using standard C code:

memcpy(&CmdBuffer[CmdBuffer_Index], &cmd, sizeof cmd);

Upvotes: 3

Related Questions