Getting a feature's field values from type VARIANT


A feature's field values are passed back as type VARIANT, requiring you to do some processing to get the actual values. The following example loops through all of a feature's fields and prints out the feature's value for each field. Only certain field types are handled by the code shown here (for example, 2-byte integers, 4-byte integers, and BSTR strings); however, you could choose to handle other types as determined by the needs of your application.
For the sake of simplicity, the code snippets given don't always check HRESULT's, although as a developer you should always do so.
[C++]
// ipFeature is of type IFeaturePtr, and we assume it has already been declared and instantiated above
IFieldsPtr ipFields;
hr = ipFeature->get_Fields(&ipFields);
long fieldCount;
hr = ipFields->get_FieldCount(&fieldCount);
IFieldPtr ipField;
CComVariant fieldValue;

for (long i = 0; i < fieldCount; i++)
{
  hr = ipFields->get_Field(i, &ipField);
  hr = ipFeature->get_Value(i, &fieldValue);

  // Get field's value based on its type
  switch (fieldValue.vt)
  {
    case VT_I2:
      std::cerr << fieldValue.iVal << std::endl;
      break;
    case VT_I4:
      std::cerr << fieldValue.lVal << std::endl;
      break;
    case VT_R4:
      std::cerr << fieldValue.fltVal << std::endl;
      break;
    case VT_R8:
      std::cerr << fieldValue.dblVal << std::endl;
      break;
    case VT_BSTR:
      std::wcerr << fieldValue.bstrVal << std::endl;
      break;
    default:
      std::wcerr << "Field type not supported.\n";
      break;
  }
}