我有一个结构:
typedef struct Image {
byte height;
byte width;
byte data[];
} Image;
我创建了两个图像:
static const __flash Image GRID = {
.width = 16,
.height = 8,
.data = {
0x10, 0x10, 0x28, 0x28, 0x44, 0x44, 0x82, 0x82, ...
}
};
static const __flash Image HOUSE1 = {
.width = 24,
.height = 24,
.data = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ...
}
};
然后我创建一个指向图像的指针数组:
static const __flash Image *IMAGES[] = {
&GRID,
&HOUSE1,
};
我可以使用
draw_image()
函数绘制图像:void main(void)
{
draw_image(IMAGES[0], 16, 16);
}
我有一张地图:
typedef struct Map {
word cols;
word rows;
byte tiles[];
} Map;
static const __flash Map level_1 = {
.cols = 16,
.rows = 8,
.tiles = {
0,0,1,0,...
.tiles
字段是IMAGES
数组中的索引列表。我这样做是因为我的引擎不知道哪些图像可以不被告知:void draw_map(const Map __memx *map, const Image __memx *tileset[]);
{
...
draw_image(tileset[map->tiles[index]], x, y);
...
}
打电话给thusly:
void main(void)
{
draw_map(&level_1, &IMAGES[0]);
}
编译器不喜欢这样,并给出不兼容的指针类型警告。地图未绘制:
note: expected
‘const __memx Image ** {aka const __memx struct Image **}’
but argument is of type
‘const __flash Image ** {aka const __flash struct Image **}’
我试过从声明中删除
[]
:void draw_map(const Map __memx *map, const __memx Image *tileset);
但这让我在调用
draw_map()
调用时出错:error: incompatible type for argument 1 of ‘draw_image’
draw_image(tileset[0], c*8+(64 - r*8), r*8);
^
tile-engine.c:63:6: note: expected
‘const __memx Image * {aka const __memx struct Image *}’ but argument is of type
‘Image {aka const __memx struct Image}’
我哪里做错了?
void draw_image(const Image __memx *image, int x, int y)
{
byte rows = image->height>>3;
byte cols = image->width>>3;
for(byte r=0 ; r<rows ; r++)
{
for(byte c=0 ; c<cols ; c++)
{
draw_tile(&image->data[(r*cols+c)*8], &image->data[(r*cols+c)*8], x+(c*8), y+(r*8));
}
}
}
最佳答案
问题似乎正是编译器所识别的:您正在将一个__flash
指针传递给一个需要__memx
指针的函数。
如果您将draw_map的签名更改为
void draw_map(const Map __memx *map, const Image __flash *tileset[])
那就行了。
好吧,既然编译器可以接受第一个参数的
__flash
指针(也被定义为__memx
),那么为什么这是必要的呢?原因是第一个指针按值传递,而第二个指针按引用传递(
tileset
是指向__memx
指针的指针)。根据AVR文档,
__flash
指针是进入(显然)闪存的16位指针,而__memx
指针是24位指针,可以指向闪存或静态RAM中的位置。编译器看起来足够聪明,可以在按值传递时将16位
__flash
指针提升为24位__memx
指针(类似于如何将16位短整型或长整型提升为32位整型),但它不能使存储在内存(在IMAGES
数组中)中的16位指针扩展为24位。由于
__memx
指针的使用速度比__flash
指针慢(显然编译器必须检查实际指针是否指向flash或static RAM,并为每个指针使用不同的指令),如果您知道图像和地图数据将始终处于flash状态,只需传递__flash
指针即可。关于c - 将指针传递给指向C结构的指针数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54505474/