Hi there,

 

I have been trying to wrap my c library to PHP. But I am stuck at the moment with wrapping C struct array. Could any expert out there me out ?  Many thanks in advance!!!!!

 

Basically, with struct Vector, I have two functions. One is taking 2 Vectors  and add them. The other is taking an array of Vectors  and print it out. I have no trouble with the 1st function. But for the second function I have no clue what is wrong.

 

I am using SWIG 1.3.36. I use the following commands to build it.

SWIG –php5 –make example.i

Make

 

Here is all my files.

 

File : example.h

============================================================================================================

#include <stdlib.h>

#include <stdio.h>

 

typedef struct Vector

{

    double x,y,z;

} Vector;

 

extern void add ( Vector *a, Vector *b, Vector *c );

extern void print_vector_array ( long num, Vector *va );

 

 

File : example.c

============================================================================================================

#include "example.h"

 

void add ( Vector *a, Vector *b, Vector *c )

{

    c->x = a->x + b->x;

    c->y = a->y + b->y;

    c->z = a->z + b->z;

}

 

void print_vector_array ( long num, Vector *va )

{

    long i = 0;

    for ( i = 0; i < num; ++i)

    {

        printf (" %f %f %f\n", va[i].x,  va[i].y, va[i].z);

    }

}

 

 

File : example.i

============================================================================================================

%module example

%{

#include "example.h"

%}

 

typedef struct Vector

{

    double x, y,z;

} Vector;

 

extern void add (Vector *a, Vector *b, Vector *c );

 

%include "carrays.i"

%array_functions (Vector *, VectorArray );

extern voi print_vector_array (int num, Vector *va );

 

File: test.php

============================================================================================================

<?php

require_once 'example.php';

 

$a = new Vector();

$a->x = 1;

$a->y = 1;

$a->z = 1;

 

$b = new Vector ();

$b->x = 2;

$b->y = 2;

$b->z = 2;

 

$c = new Vector ();

add ( $a, $b, $c );

echo "c->x = ".$c->x." c->y = ".$c->y." c->z = ".$c->z."\n";

// The above code works fine

 

// The rest does not work !

$va = new_VectorArray (3);

VectorArray_setitem ( $va, 0, $a );

VectorArray_setitem ( $va, 1, $b );

VectorArray_setitem ( $va, 2, $c );

 

$d = VectorArray_getitem ($va, 1 );

echo "d->x = ".$d->x."d->y = ".$d->y."d->z = ".$d->z."\n";

 

print_vector_array ( 3, $va );

?>