通过函数传递 void 指针,然后转换为所需的类型

问题描述 投票:0回答:2

我正在练习 C,但使用指针仍然不太安全。在下面我写了一段代码(没有编译它,只是伪代码) 假设我有类似的东西:

typedef struct
{
   uint8 A;
   uint8 B;
}myDataStruct;

typedef struct _data_info
{
    uint8t*           bufAddr;
    uint32t           bufSize;

}data_info;


int getInfo(VOID * pMsg, int32 *size); //Function returns the pointer to the data 
buffer. This function is declared somewhere outside this module

static void myFunction(void* pData);

static void OperateOnData(myDataStruct* pData)


main()
{
    data_info inf;   //Declare instance of data_info

    getInfo(&inf,sizeof(data_info))   //Function holds the information where data of interest is stored

    myFunction((void*)data_info.bufAddr);  //Here I want to pass the address of the data in order to operate on it
}

static void myFunction(void* pData)
{ 
  /*Furtheremore I want to pass the pointer to next function where the data will be used*/
  OperateOnData((myDataStruct*)pData)
}

static void OperateOnData(myDataStruct* pData)
{
    /*do something with pData*/

    uint8 x;
    uint8 y;

    x = pData->A
    Y = pData->B 

 /*....*/
 /*....*/
}

这里的问题是我是否正确提供了从调用 myFunction() 到 OperateOnData() 函数,这样我就可以使用 getInfo() 返回的地址中保存的数据。是否可以将 myFunction 的参数设置为 *void,然后将其转换为所需的类型(如 myDataStruct)?

c pointers casting
2个回答
0
投票

一般来说,指针双关是危险的,你应该使用

memcpy
来保证安全,并且你不会调用未定义的行为。

static void myFunction(void* pData)
{ 
    myDataStruct Data;
    memcpy(&Data, pData, sizeof(Data));
    OperateOnData(&Data);
}

0
投票

因为你声明

inf
如下:

data_info inf;

所以

&inf
data_info*
的类型。

所以当你使用

getInfo(&inf,sizeof(data_info))

用于

getInfo
功能

int getInfo(VOID * pMsg, int32 *size);

应该是

int getInfo(data_info* pMsg, int32 size);  //sizeof(data_info) is type of size_t that is not pointer

对于

myFunction

如果你

Here I want to pass the address of the data in order to operate on it

使用

&
获得
address of the data

myFunction(&(data_info.bufAddr));

所以

static void myFunction(void* pData);

应该是

static void myFunction(uint8t** pData);

关于

/*Furtheremore I want to pass the pointer to next function where the data will be used*/
OperateOnData((myDataStruct*)pData)

应该是

/*Furtheremore I want to pass the pointer to next function where the data will be used*/
OperateOnData(&pData)

下图为@0___________

© www.soinside.com 2019 - 2024. All rights reserved.