Skip to content

Incorrect element-count calculation in SafeArray.cpp numElements() cause 2D and higher SafeArrays to fail #48

@EJP286CRSKW

Description

@EJP286CRSKW
static int numElements(SAFEARRAY *psa)
{
  int nDims = SafeArrayGetDim(psa);
  int elems = 0;
  for(int i=1;i<=nDims;i++) {
    long lb, ub;
    SafeArrayGetLBound(psa, i, &lb);
    SafeArrayGetUBound(psa, i, &ub);
    elems += ub - lb + 1;
  }
  return elems;
}

This calculation is incorrect, as the number of elements in an mxn array is mxn, not m+n. It happens to be correct in the 1D case only, but not beyond. The effect of this is that fromXXXArray() and toXXXArray() don't work for 2D and higher.

Solution:

static int numElements(SAFEARRAY *psa)
{
  int nDims = SafeArrayGetDim(psa);
  int elems = 0;
  for(int i=1;i<=nDims;i++) {
    long lb, ub;
    SafeArrayGetLBound(psa, i, &lb);
    SafeArrayGetUBound(psa, i, &ub);
    if (elems == 0)
        elems = 1;
    elems *= ub - lb + 1;
  }
  return elems;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions