This forum has been archived. All content is frozen. Please use KDE Discuss instead.

Convert Op to actual values

Tags: None
(comma "," separated)
Horus
Registered Member
Posts
296
Karma
0
OS

Convert Op to actual values

Mon Nov 21, 2016 4:35 pm
Hello,

I have this piece of code
Code: Select all
#include <Eigen/Dense>

int main(int argc, char *argv[])
{
  Eigen::Vector3d x(1, 2, 3);
  double* pdx = (x.array() + 1).data();
}


It does not compile, because:
% clang++ -std=c++11 test.cpp
test.cpp:6:33: error: no member named 'data' in 'Eigen::CwiseUnaryOp<Eigen::internal::scalar_add_op<double>, const Eigen::ArrayWrapper<Eigen::Matrix<double, 3, 1, 0, 3, 1> > >'
double* pdx = (x.array() + 1).data();
~~~~~~~~~~~~~~~ ^
1 error generated.


What is the best way to work around that? Can I force evaluation of the CwiseUnaryOp to something which has actual values and can return the underlying data?

Thanks!
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: Convert Op to actual values

Mon Nov 21, 2016 9:51 pm
You could do ptr = (x.array() + 1).eval().data(); but that would be useless as ptr would then immediately reference a dead object. So you need to name the temporary:

Vector3d tmp = x.array() + 1;
ptr = tmp.data();
Horus
Registered Member
Posts
296
Karma
0
OS

Re: Convert Op to actual values

Tue Nov 22, 2016 8:19 am
It also works using a static cast:

Code: Select all
double* pdx = static_cast<Eigen::VectorXd>(x.array() + 1).data();
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: Convert Op to actual values

Tue Nov 22, 2016 9:26 am
Please don't do that !! because right after this statement pdx reference a freed memory. It might appear to work if no memory operation wrote in this buffer, but in general this won't work, and running your program within a memory debugger (e.g. valgrind) will show you the issue.
Horus
Registered Member
Posts
296
Karma
0
OS

Re: Convert Op to actual values

Tue Nov 22, 2016 10:07 am
Ok, I see you're right.

It would be nice to have a method that force an expression template to be evaluated, so that you can call methods like data() on it.
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: Convert Op to actual values

Tue Nov 22, 2016 10:50 am
That's the .eval() method, but you cannot use it in your context.


Bookmarks



Who is online

Registered users: Bing [Bot], Google [Bot], Sogou [Bot]