[C++-sig] C++ float[4][4] in Python

Mike Wyatt mwyatt at wi.rr.com
Sat May 20 17:48:49 CEST 2006


I'm almost finished with my  C++ Matrix class that I'm using as an 
extension module in Python (using Boost.Python).  I store the matrix' 
values in a
float[4][4] array, which I need to make available to my PyOpenGL calls 
(glLoadMatrix and glMultMatrix, specifically):

    public class Matrix
    {
    public:
        /* methods */
    private:
        float m[4][4];    // 4x4 matrix array
    }

    BOOST_PYTHON_MODULE(matrix)
    {
        class_< Matrix >("Matrix")
            // other defs
            .def_readonly("m", &Matrix::m)
       ;
    }

My problem is that attempting to use my public array results in the 
following error:

     TypeError: No to_python (by-value) converter found for C++ type: 
float [4][4]

I couldn't find a way around that error, so I modified my C++ class to 
return a tuple using Boost.Python's "make_tuple" function:

    pyTuple = make_tuple(
        make_tuple(m[0][0], m[0][1], m[0][2], m[0][3]),
        make_tuple(m[1][0], m[1][1], m[1][2], m[1][3]),
        make_tuple(m[2][0], m[2][1], m[2][2], m[2][3]),
        make_tuple(m[3][0], m[3][1], m[3][2], m[3][3]) );

This works fine, but I think that I can improve performance by not 
allocating five tuples everytime the matrix changes.

*I see two solutions to my problem:
*
1) Find a way for Python to understand a float[4][4].
2) Instead of allocating five tuples everytime the matrix changes, can I 
create my tuples in the class constructor, then simply set the values 
when necessary?  The following code doesn't work, but should illustrate 
what I want to do:

tuple Matrix::ToTuple()
{
    pyTuple[0][0] = m[0][0];
    pyTuple[0][1] = m[0][1];
    pyTuple[0][2] = m[0][2];
    pyTuple[0][3] = m[0][3];

    pyTuple[1][0] = m[1][0];
    pyTuple[1][1] = m[1][1];
    pyTuple[1][2] = m[1][2];
    pyTuple[1][3] = m[1][3];

    pyTuple[2][0] = m[2][0];
    pyTuple[2][1] = m[2][1];
    pyTuple[2][2] = m[2][2];
    pyTuple[2][3] = m[2][3];

    pyTuple[3][0] = m[3][0];
    pyTuple[3][1] = m[3][1];
    pyTuple[3][2] = m[3][2];
    pyTuple[3][3] = m[3][3];

    return pyTuple;
}

The above code compiles fine, but throws the following error when I run 
the ToTuple() method in Python:

    TypeError: object does not support item assignment

Any thoughts?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20060520/572374a7/attachment.htm>


More information about the Cplusplus-sig mailing list