gpt4 book ai didi

c++ - 在 C++ 中从 C 库正确初始化 typedef 结构

转载 作者:太空宇宙 更新时间:2023-11-04 01:03:23 29 4
gpt4 key购买 nike

我想在我的 C++ 项目中包含一个库(控制 Raspberry Pi 上的 RGB LED 灯条)。导入库工作正常,但我在正确初始化某些结构方面遇到了很多问题。我什至不知道在哪里可以找到正确的语法,我进行了很多谷歌搜索,但并没有走得太远。

我首先想要的是运行库附带的示例应用程序。请参阅:https://github.com/richardghirst/rpi_ws281x/blob/master/main.c

我的主要问题是这个。在 C++ 方式下如何完成?

ws2811_t ledstring =
{
.freq = TARGET_FREQ,
.dmanum = DMA,
.channel =
{
[0] =
{
.gpionum = GPIO_PIN,
.count = LED_COUNT,
.invert = 0,
.brightness = 255,
},
[1] =
{
.gpionum = 0,
.count = 0,
.invert = 0,
.brightness = 0,
},
},
};

它的初始化方式是特定于 C 的,并且不能在任何当前的 C++ 标准中编译。请参阅:Why does C++11 not support designated initializer list as C99?到目前为止,我只使用过自己的结构,也从未使用过 typedef,所以我只是对此处定义结构的方式感到困惑。

上面初始化的结构体就是这样定义的。请参阅:https://github.com/richardghirst/rpi_ws281x/blob/master/ws2811.h

typedef struct
{
int gpionum; //< GPIO Pin with PWM alternate function
int invert; //< Invert output signal
int count; //< Number of LEDs, 0 if channel is unused
int brightness; //< Brightness value between 0 and 255
ws2811_led_t *leds; //< LED buffers, allocated by driver based on count
} ws2811_channel_t;

typedef struct
{
struct ws2811_device *device; //< Private data for driver use
uint32_t freq; //< Required output frequency
int dmanum; //< DMA number _not_ already in use
ws2811_channel_t channel[RPI_PWM_CHANNELS];
} ws2811_t;

我试过的是这样的:

ws2811_led_t matrix[WIDTH][HEIGHT];
ws2811_channel_t channel0 = {GPIO_PIN,LED_COUNT,0,255,*matrix};
ws2811_t ledstring = {nullptr,TARGET_FREQ,DMA,channel0};

当我实际“渲染”到 LED 灯条时,编译但导致 malloc 错误:

int x, y;

for (x = 0; x < WIDTH; x++)
{
for (y = 0; y < HEIGHT; y++)
{
cout << "LEDs size: " << (y * WIDTH) + x << endl;
ledstring.channel[0].leds[(y * WIDTH) + x] = matrix[x][y];
}
}

循环构造完成后出现此错误消息:

malloc(): memory corruption (fast): 0x021acaa8

最佳答案

您应该能够使用以下初始化程序:

ws2811_t ledstring =
{
nullptr,
TARGET_FREQ,
DMA,
{
{ GPIO_PIN, 0, LED_COUNT, 255 },
{ 0 }
}
};

关于c++ - 在 C++ 中从 C 库正确初始化 typedef 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30078300/

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