gpt4 book ai didi

c++ - 将指针转换为二维数组

转载 作者:行者123 更新时间:2023-11-30 04:32:12 25 4
gpt4 key购买 nike

我从 C# 代码调用 C++ 方法,并将二维数组第一个元素的指针和数组的维度传递给 C++ 函数:

C#代码

fixed (bool* addressOfMonochromeBoolMatrixOfBitmap = &monochromeBoolMatrixOfBitmap[0, 0]
{
NativeGetUniquenessMatrixOfBitmap(addressOfMonochromeBoolMatrixOfBitmap, Width, Height);
}

C++代码

extern "C" __declspec(dllexport) void NativeGetUniquenessMatrixOfBitmap ( bool* addressOfMonochromeBoolMatrixOfBitmap, 
int boolMatrixWidth, int boolMatrixHeight)
{
}

在 C++ 代码中,我想将 bool* 指针转换为二维数组,以便使用常规数组语法访问元素:someArray[1][4]。我试过这段代码:

bool (*boolMatrix)[boolMatrixWidth][boolMatrixHeight] = (bool (*)[boolMatrixWidth][boolMatrixHeight])addressOfMonochromeBoolMatrixOfBitmap;

但它不会编译并给出消息“预期的常量表达式”。

请分享任何想法。谢谢。

最佳答案

在 C++ 二维数组中,只有一个数组维度可以来自变量,另一个必须是常量。所以你必须保留指针并手动计算每个像素的地址。

而且我担心您必须交换高度和宽度,即正确的可能是 [height][width]。如果是这样,那么高度可以是可变的,但宽度必须是恒定的。如果它不是常量,则必须保留 bool* 指针并计算每一行的地址,如 row = address + width*y 然后你可以使用 row[x] 以访问行中的特定项目。

//we prepare row pointer to read at position x,y 
bool *row = addressOfMonochromeBoolMatrixOfBitmap + boolMatrixWidth * y;

//example: read from x,y
bool value_at_xy = row[x];

//example: move to next row
row += boolMatrixWidth;

关于c++ - 将指针转换为二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7799766/

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