您的位置:首页 > Web前端

使用多维safearray时值得注意的地方

2005-03-14 15:55 323 查看
今天中午给safearray弄得晕乎乎的,最后发现msdn的safearray概述里明确提到了下面这段东西,让俺体会到了不先看文档的后果

The base type of the array is indicated by VT_ tag | VT_ARRAY. The data referenced by an array descriptor is stored in column-major order, which is the same ordering scheme used by Visual Basic and FORTRAN, but different from C and Pascal. Column-major order is when the left-most dimension (as specified in a programming language syntax) changes first.

比如,vb里定义了如下的数组

ReDim r(1 To 2, 1 To 3) As Long

r(1, 1) = 11

r(1, 2) = 12

r(1, 3) = 13

内存的排列其实是

11
0
12
0
13
0
以c的观点来看,是这样一个矩阵

110
120
130
用SafeArrayGetElement取值时,分别用索引 {1,1}  {1,2}  {1,3} 来获得r (1,1), r(1,2), r(1,3)。

msdn对索引的描述如下:

rgIndices Pointer to a vector of indexes for each dimension of the array. The right-most (least significant) dimension is rgIndices[0]. The left-most dimension is stored at rgIndices[psa->cDims – 1].

这句话太模糊了,俺最初就是给它搞昏的,现在看来其中所谓的right-most是以c数组的观点来看的。如果用safearraylock/unlock直接指针存取数值时,设上下标分别为LBound1,LBound2,UBound1,UBound2,大小为Dim1, Dim2,索引为Index1, Index2,则用

*(pData + (Index2 - LBound2) * Dim1 + (Index1 - LBound1));

来取 arr(Index1, Index2) 的值。

最后贴一下构建开头那个数组的vc代码

 SAFEARRAYBOUND saBounds[2] = { { 2, 1 }, { 3,1 } };

 SAFEARRAY *psa = SafeArrayCreate(VT_I4, 2, saBounds);

 long lIndices[2] = { 1, 1 };

 long nValue = 11;

 SafeArrayPutElement(psa, lIndices, &nValue);

 lIndices[1] = 2;

 nValue = 12;

 SafeArrayPutElement(psa, lIndices, &nValue);

 lIndices[1] = 3;

 nValue = 13;

 SafeArrayPutElement(psa, lIndices, &nValue);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: