Search code examples
c++eigen3

eigen3 type cast / copy from pointer (overflow uint8_t)


i get a uint8_t * array (which is fixed defined) and want to use them with a Eigen3 Matrix.

I started using

typedef Eigen::Matrix<uint8_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Matrix8u;

with a memcpy to .data()

but later i noticed that for example .sum() I'm getting an overflow.

Is there a way to make a fast copy between a uint8_t * and a int32_t ? - with Eigen::Map ?

Greetings


Solution

  • I'd use Eigen::Map to map your array onto a Matrix8u and then cast it to something like Matrix32i.

    Assuming your data is in a form of an array data[] = {0, 1, 2, ...} here is sample code:

    typedef Eigen::Matrix<uint8_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Matrix8u;
    typedef Eigen::Matrix<int32_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Matrix32i;
    
    uint8_t data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
    
    Matrix32i m32i = Eigen::Map<Matrix8u>(data, rows, cols).cast<Matrix32i::Scalar>();
    

    And of course rows*cols must equal the length of your data array.