我正在尝试将 Eigen 与 cppyy 一起使用并来回转换为 numpy,但遇到了障碍,
当无法在 python 中分配给函数调用时,如何通过引用设置值?
以这段C++代码为例:
Eigen::Matrix4d matrix = Eigen::Matrix4d::Identity();
matrix(0, 0) = 2.0;
现在在Python中:
matrix = cppyy.gbl.Eigen.Matrix4d.Identity()
matrix(0, 0) = 2.0 # error, cannot assign to function call
matrix.row(0)[0] = 2.0 # error, setitem operator does not work correctly in cppyy here
不仅仅是 Eigen,任何返回标准类型(double、float 等)非常量引用的函数都存在此问题。 例如:
class MyClass {
public:
double& value() { return m_value; }
const double& value() const { return m_value; }
private:
float m_value{0.0};
};
这方面的标准做法是什么?
cppyy 将 C++ 对象的赋值运算符公开为名为 __assign__
你可以使用
matrix(0, 0).__assign__(2.0)
在
matrix(0, 0)
返回的任何对象上调用赋值运算符。