【发布时间】:2012-06-13 12:52:12
【问题描述】:
假设我有以下简单的结构:
struct Vector3
{
double x;
double y;
double z;
};
然后我创建了一个顶点列表:
std::vector<Vector3> verticesList;
除此之外,我还需要使用第三方库。该库有一个具有以下签名的函数:
typedef double[3] Real3;
external void createMesh(const Real3* vertices, const size_t verticesCount);
将verticesList 转换为可以作为vertices 参数传递给createMesh() 的最佳方法是什么?
目前我使用以下方法:
static const size_t MAX_VERTICES = 1024;
if (verticesList.size() > MAX_VERTICES)
throw std::exception("Number of vertices is too big");
Real3 rawVertices[MAX_VERTICES];
for (size_t vertexInd = 0; vertexInd < verticesList.size(); ++vertexInd)
{
const Vector3& vertex = verticesList[vertexInd];
rawVertices[vertexInd][0] = vertex.x;
rawVertices[vertexInd][1] = vertex.y;
rawVertices[vertexInd][2] = vertex.z;
}
createMesh(rawVertices, verticesList.size());
但这肯定不是解决问题的最佳方法。
【问题讨论】:
-
这种方法具有可读性强的优点。您可能会发现 Vector3 数组在内存中的排列方式与浮点数组完全相同;重新解释演员表或 memcpy 可能会以更简短的方式解决您的问题。但是,我懒得自己检查。
-
我想你可以为
Vector3->Real3实现一个转换运算符并传递&verticesList[0]。 -
@chris:来自
Vector3的转换->Real3不会从Vector3*转换->Real3* -
@DavidRodríguez-dribeas,哎呀,对。我在考虑
reinterpet_cast,但转换似乎更合适(如果可行的话)。