Search code examples
c++matlabvisual-studiomex

Matlab/Mex: Conversion warning in mxarray.h


I am writing a mex function for Matlab and noticed a warning from Visual Studio 2017 during compilation. After virtually erasing everything but includes and the bare wrapper for mex-functions, I had to come to the conclusion that the warning is really pointing at the library itself:

#include <mexplus/mxarray.h>

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{

}

This snippet already triggers the warning

...\mexplus\mxarray.h(737): warning C4267: 'argument': conversion from 'size_t' to 'int', possible loss of data

I looked into the file and indeed, there is a loop iterating in size_t through a std::vector, while calling a previously defined function, that is taking an int as argument:

733:  std::vector<std::string> fieldNames() const {
734:    MEXPLUS_ASSERT(isStruct(), "Expected a struct array.");
735:    std::vector<std::string> fields(fieldSize());
736:    for (size_t i = 0; i < fields.size(); ++i)
737:      fields[i] = fieldName(i);
738:    return fields;
739:  }

The function fieldName is defined above that:

std::string fieldName(int index) const {
    const char* field = mxGetFieldNameByNumber(array_, index);
    MEXPLUS_ASSERT(field, "Failed to get field name at %d.", index);
    return std::string(field);
}

So, since the size_t to int conversion already caused some chaos in a different environment, my questions are:

  • Can I safely ignore this?
  • Is there actually a reason for anyone to write the function fieldNames()like this (or rather, require the function fieldName(int index) to take an integer as argument)?
  • Might this warning actually point to an error in my configuration file?

Solution

  • You can safely ignore this.

    Here's a nice description of why a loop might be written this way From http://en.cppreference.com/w/cpp/types/size_t:

    std::size_t is commonly used for array indexing and loop counting. Programs that use other types, such as unsigned int, for array indexing may fail on, e.g. 64-bit systems when the index exceeds UINT_MAX or if it relies on 32-bit modular arithmetic.

    The actual value of size_t, the maximum amount of memory allocatable, is going to be system dependent. The compiler looks to be casting the 0 (in i = 0) to an int and then throwing the warning, because it just reduced your usable range by half (i.e. instead of an unsigned int).

    In practice though, i can probably still index up to a value of 2^32 (this is where it gets platform dependent), and you are probably not going to be dealing with structures having that many field names.

    Might this warning actually point to an error in my configuration file?

    I don't think so.

    Can I safely ignore this?

    Yes.