shestakoffvs
shestakoffvs

Reputation: 99

matrix from C function to Python

I'm working with python and ctypes. I have a C function convert a quaternion (similar to an imaginary number) to a matrix. I know, that send result variable in function like argument it's bad tone, so how can I return matrix to python code in type array c_float*16.

float* QuaternionToMatrix(Quaternion q)
{
    float matrix[16];

    matrix[ 0] = 1.0f - 2.0f * ( q.y * q.y + q.z * q.z );
    matrix[ 1] = 2.0f * (q.x * q.y + q.z * q.w);
    matrix[ 2] = 2.0f * (q.x * q.z - q.y * q.w);
    matrix[ 3] = 0.0f;

    matrix[ 4] = 2.0f * ( q.x * q.y - q.z * q.w );
    matrix[ 5] = 1.0f - 2.0f * ( q.x * q.x + q.z * q.z );
    matrix[ 6] = 2.0f * (q.z * q.y + q.x * q.w );
    matrix[ 7] = 0.0f;

    matrix[ 8] = 2.0f * ( q.x * q.z + q.y * q.w );
    matrix[ 9] = 2.0f * ( q.y * q.z - q.x * q.w );
    matrix[10] = 1.0f - 2.0f * ( q.x * q.x + q.y * q.y );
    matrix[11] = 0.0f;

    matrix[12] = 0;
    matrix[13] = 0;
    matrix[14] = 0;
    matrix[15] = 1.0f;

    float* a = matrix;

    return a;
}

Upvotes: 2

Views: 164

Answers (1)

ecatmur
ecatmur

Reputation: 157314

You're returning a pointer to a local variable. This will cause memory corruption. I'd recommend creating a struct enapsulating your matrix and returning that:

typedef struct matrix {
    float data[16];
} matrix;

matrix QuaternionToMatrix(Quaternion q) {
    ...
}

Because this will result in copying some amount of memory (c. 512 bytes), you would probably be better off passing the matrix as an out-parameter:

void QuaternionToMatrix(Quaternion q, matrix *matrix) {
    ...
}

Upvotes: 3

Related Questions