问题描述
假设我有一个向量类:
typedef struct vec3_s
{
float x, y, z;
}
vec3;
但是,我希望能够在不将其转换为浮点数数组的情况下对其进行迭代.虽然在这种情况下强制转换是可以接受的,但我很想知道是否有任何类似 C++ 的功能在直接 C 中是可行的.例如,在 C++ 中,因为 std::vector 有下标
[]
运算符重载,我可以将它的第一个索引的地址传递给采用 void*
的函数.
But, I would like to be able to iterate through it without converting it to an array of floats. While a cast is acceptable in this case, I'm curious to see if anything along the lines of C++ like functionality is doable in straight C. For example, in C++, since std::vector< T >
has the subscript []
operator overloaded, I can pass the address of its first index to a function taking a void*
.
即
void do_something_with_pointer_to_mem( void* mem )
{
// do stuff
}
int main( void )
{
std::vector< float > v;
// fill v with values here
// pass to do_something_with_pointer_to_mem
do_some_with_pointer_to_mem( &v[ 0 ] );
return;
}
另一个更具体的例子是当调用 glBufferData(...) 是在 OpenGL 中制作的(使用 C++ 时):
Another, more concrete example is when calls to glBufferData(...) are made in OpenGL (when using C++):
glBufferData( GL_ARRAY_BUFFER, sizeof( somevector ), &somevector[ 0 ], GL_STREAM_DRAW );
那么,是否可以使用下标运算符在 C 中完成类似的操作?如果没有,我必须编写一个函数(例如,float vec3_value_at( unsigned int i )
),将它static inline
放在头文件中是否有意义?定义在?
So, is it possible to accomplish something similar in C using the subscript operator? If not, and I had to write a function (e.g., float vec3_value_at( unsigned int i )
), would it make sense to just static inline
it in the header file it's defined in?
推荐答案
如果你所有的结构域都是相同的类型,你可以使用联合如下:
If all of your structure fields are of the same type, you could use a union as following:
typedef union vec3_u
{
struct vec3_s {
float x, y, z;
};
float vect3_a[3];
}
vec3;
通过这种方式,您可以独立访问每个 x、y 或 z 字段,或者使用 vect3_a 数组迭代它们.这个解决方案在内存或计算方面没有任何成本,但我们可能离类似 C++ 的解决方案有点远.
This way you could access to each x, y or z field independently or iterate over them using the vect3_a array. This solution cost nothing in term of memory or computation but we may be a bit far from a C++ like solution.
这篇关于用于像数组一样遍历结构成员的 C 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!