gpt4 book ai didi

通过引用传递结构而不是指向缓冲区的指针的转换问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:33:03 26 4
gpt4 key购买 nike

通过引用传递 struct 时出现转换错误。将指针传递给缓冲区工作正常。 getstuff() 函数实际上是 libusb_claim_interface() 去掉了不相关的部分。我正在尝试从插入 Linux 机器的 USB 设备取回一大块数据。

数据按照这个struct进来:

typedef struct mystruct {
unsigned char a;
unsigned short b;
unsigned char c;
unsigned char d;
... /* 40 more members of unsigned char */
} mystruct_t;

但是,我使用的代码传递了一个无符号字符缓冲区。然后缓冲区需要设置每个单独的结构成员。

例如:

getstuff(unsigned char *data, int length);
void foo(void)
{
unsigned char apple;
unsigned short banana;
unsigned char cherry;
unsigned char date;
...
unsigned char buffer[44];

sendstuff(...);
getstuff(buffer, 44);
apple = buffer[0];
banana = buffer[1];
cherry = buffer[2];
date = buffer[3];
...
}

我不想那样做,而是想实际定义一个 struct(见上文)并传递一个引用,然后明智地访问成员,如下所示:

getstuff(unsigned char *data, int length);
void foo(void)
{
unsigned char apple;
unsigned short banana;
unsigned char cherry;
unsigned char date;
...
mystruct_t *fruits;

sendstuff(...);
getstuff((unsigned char) fruits, sizeof(mystruct_t));
apple = fruits->a;
banana = fruits->b;
cherry = fruits->c;
date = fruits->d;
...
}

但这行不通。首先我在编译时得到这个:

warning: cast from pointer to integer of different size [-Wpointer
-to-int-cast]
(unsigned char) fruits,

warning: passing argument 3 of ‘getstuff’ makes pointer from
integer without a cast [-Wint-conversion]

然后,这个(在解析 libusb.h 时抛出):

note: expected ‘unsigned char *’ but argument is of type ‘unsigned char’
int LIBUSB_CALL libusb_bulk_transfer(libusb_device_handle *dev_handle,

当我运行程序时,设备似乎发回了 21906 字节而不是预期的 44 字节。如果我将 fruits 转换到 (unsigned char *),程序编译没有提示,但随后我返回 21900 到 22060 字节之间的任何位置。我可以像在原始代码中那样简单地传递一个无符号字符数组来“解决”这个问题,然后这样做将指针复制到 mystruct_t *fruits:

fruits = (mystruct_t *) buffer;

但我真的很想知道发生了什么以及为什么我在转换结构时遇到这么多麻烦。

最佳答案

getstuff((unsigned char) fruits, sizeof(mystruct_t)); => getstuff((unsigned char *) fruits, sizeof(*fruits));

fruits = (mystruct_t *) buffer; 这个叫做“指针双关”,不安全,不可移植,通常是 UB

另一个问题是您没有为 fruits 结构分配内存。

你可以:

  mystruct_t fruits;
....
getstuff((unsigned char *)&fruits, sizeof(fruits));

  mystruct_t *fruits = malloc(sizeof(*fruits));
/* malloc checks + .... */
getstuff((unsigned char *)fruits, sizeof(*fruits));

关于通过引用传递结构而不是指向缓冲区的指针的转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51794899/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com