c++freeimage

How to set and get value of fipTag


My attempt:

fipTag t;
t.setType(FIDT_LONG);
t.setKey("FrameTime");
long l = 128;
t.setValue(&l);

supposedly this set the tag value to 128 long

However..

const long * lo = static_cast<const long*> ( t.getValue() );
cout << "t.getValue() " << *lo << " ?? doesn't look right" << endl; // 847909360
cout << "l == *lo " << (l == *lo) << endl;                          // false

What's up? How do we correctly set and get the value of a fipTag in FreeImagePlus?

The unhelpful documentation: http://freeimage.sourceforge.net/fip/classfipTag.html#a34b0b079bc222aaf4b4d1ad4ce423f82

The whole code:

#include <FreeImagePlus.h>
#include <iostream>

using namespace std;
int main(void)
{
    fipTag t;
    t.setType(FIDT_LONG);
    t.setKey("FrameTime");
    long l = 128;
    t.setValue(&l);
    const long * lo = static_cast<const long*> ( t.getValue() );
    cout << "t.getValue() " << *lo << " ?? doesn't look right" << endl;
    cout << "l == *lo " << (l == *lo) << endl;

    return 0;
}

Solution

  • With the type set to FIDT_LONG, setTag (which is just a wrapper for FreeImage_SetTagValue) expects an array of 4 bytes (32-bit) unsigned integers. long is usually 8 bytes on 64-bit systems.

    Also, the total byte size of the value and how many elements it contains must be explicitly set.

    #include <iostream>
    #include <iterator> // std::size (C++17 or newer)
    
    #include <FreeImagePlus.h>
    
    int main()
    {
      const uint32_t writeValue[] {123, 456};
    
      fipTag t;
      t.setKey("FrameTime");
      t.setType(FIDT_LONG);
      t.setCount(std::size(writeValue)); // number of elements in the array
      t.setLength(sizeof(writeValue));   // size of the entire array
      // length must be count * expected size for FIDT_LONG (4)
    
      if(t.setValue(writeValue)) {
        auto readValue = static_cast<const uint32_t *>(t.getValue());
        std::cout << "t.getValue() " << readValue[0] << std::endl;
      }
    
      return 0;
    }