[C++-sig] howto convert a python list to a C++ matrix
Stefan Seefeld
stefan.seefeld at orthosoft.ca
Wed Oct 9 22:27:14 CEST 2002
hi there,
I'm trying to define a matrix constructor that
takes a python list. I want to be able to write
> matrix = Matrix([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]])
where Matrix is a C++ type. Obviously I need a factory
such as 'Matrix factory(object);' or similar.
But how am I to extract the elements of the list(s) in
boost.python style ? And how should I raise a TypeError
if I don't find what I'm looking for ?
Here is a first attempt:
Matrix factory(python::list &l)
{
float matrix[16];
assert(l.length() == 4);
for (size_t i = 0; i != 4; ++i)
{
python::list row = extract<python::list>(l[i]);
assert(row.length() == 4);
for (size_t j = 0; j != 4; ++j)
{
matrix[4*i + j] = row[j];
}
}
return Matrix(matrix);
}
But 'length()' doesn't appear to exist, and the asserts
should be replaced with some (python) exceptions that
indicate a type error or similar.
More information about the Cplusplus-sig
mailing list