<分区>
我正在编写一个应用程序,该应用程序使用 C++ 进行计算,然后使用 pybind11 将多维结果作为 numpy 数组返回。来自documentation pybind 和来自 examples在网上看到,numpy 数组的创建基本上是传递数据数组的指针并包含步幅的详细信息。然而,在 C++ 部分,我并不热衷于使用一维 array
和使用一些花哨的索引,但我宁愿使用结构。这让我开始思考是否可以将放置在连续内存中的(同质)变量视为 array
的一部分。
我的思路是这样的。 array
的元素放置在连续内存中。 struct
的元素也按照声明的顺序连续放置(不涉及填充时)。所以从内存放置的角度来看,以下四个变量声明是相同的,例如如果我要将指针指向第一个元素,那么我可以通过一次执行一个整数步来遍历所有元素:
struct struct_array
{
int elem[4] = {};
};
struct struct_ints
{
int a = {};
int b = {};
int c = {};
int d = {};
};
// integer matrix of shape 3x4
int one_dim_array[3 * 4] = {};
int two_dim_array[3][4] = {};
struct_array array_of_struct_arrays[3] = {};
struct_ints array_of_struct_ints[3] = {};
这是我的测试代码,表明我的问题的答案是肯定的。它做一些地址打印、设置和读取元素。
#include <iostream>
struct struct_array
{
int elem[4] = {};
};
struct struct_ints
{
int a = {};
int b = {};
int c = {};
int d = {};
};
int main(void)
{
const int rows = 3;
const int cols = 4;
int one_dim_array[rows * cols] = {};
int two_dim_array[rows][cols] = {};
struct_array array_of_struct_arrays[rows] = {};
struct_ints array_of_struct_ints[rows] = {};
std::cout << sizeof(int) << " is the size of an int in bytes\n";
std::cout << "\nOne dim array\n";
for (int i = 0; i < 12; ++i)
{
one_dim_array[i] = i;
std::cout << &one_dim_array[i] << "\n";
}
std::cout << "\nTwo dim array\n";
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < cols; ++j)
{
two_dim_array[i][j] = i * cols + j;
std::cout << &two_dim_array[i][j] << "\n";
}
}
std::cout << "\nArray of struct arrays\n";
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < cols; ++j)
{
array_of_struct_arrays[i].elem[j] = i * cols + j;
std::cout << &array_of_struct_arrays[i] << " " << &array_of_struct_arrays[i].elem[j] << "\n";
}
}
std::cout << "\nArray of struct ints\n";
for (int i = 0; i < rows; ++i)
{
array_of_struct_ints[i].a = i * cols + 0;
array_of_struct_ints[i].b = i * cols + 1;
array_of_struct_ints[i].c = i * cols + 2;
array_of_struct_ints[i].d = i * cols + 3;
std::cout << &array_of_struct_ints[i] << " " << &array_of_struct_ints[i].a << "\n";
std::cout << &array_of_struct_ints[i] << " " << &array_of_struct_ints[i].b << "\n";
std::cout << &array_of_struct_ints[i] << " " << &array_of_struct_ints[i].c << "\n";
std::cout << &array_of_struct_ints[i] << " " << &array_of_struct_ints[i].d << "\n";
}
for (int i = 0; i < 4; ++i)
{
// Maybe using a reinterpret_cast would be more modern
void *void_p = nullptr;
switch (i)
{
case 0:
void_p = &one_dim_array;
std::cout << "\nOne dim array\n";
break;
case 1:
void_p = &two_dim_array;
std::cout << "\nTwo dim array\n";
break;
case 2:
void_p = &array_of_struct_arrays;
std::cout << "\nArray of struct arrays\n";
break;
case 3:
void_p = &array_of_struct_ints;
std::cout << "\nArray of struct ints\n";
}
int *int_p = (int *)void_p;
for (int i = 0; i < 12; ++i)
{
std::cout << *(int_p + i) << "\n";
}
}
std::cout << "Hello world!";
return 0;
}
这是对的还是我遗漏了什么?你对这件事有什么看法? (除此之外,我应该切换到 std::array。) 感谢您的宝贵时间!