Как передать массив объектов с помощью PHPCPP, пройти через каждый объект и вернуть ассоциативный массив

Недавно я начал изучать PHPCPP - библиотеку C++ для разработки расширений PHP и попыток понять:

  1. как передать массив объектов из php в C++ через библиотеку PHPCPP, так как примеры дают только информацию о массивах и объектах отдельно,
  2. тогда как перебрать каждый объект в C++
  3. и как вернуть ассоциативный массив обратно в PHP

Может ли кто-нибудь указать мне правильное направление?

Я придумал этот пример, но мне нужна помощь:

class Curve{
 public :
    double shape;
    double peak;
    double tpeak;
    double start;
    double lag;
    double index;
};

Php::Value example1(Php::Parameters &params) { 
    vector<Curve> c = params[0];

    //create an associative array and return to php
    std::map< std::string, std::map<std::string, std::map<std::string, std::map<std::string, std::double>>> > data;
    // loop through array of objects here or do something with an array
    ...
    data[c.shape][c.peak][c.tpeak][c.start] = 1/12 * c.index;

    return data;
}


extern "C" {
    PHPCPP_EXPORT void *get_module() {
        static Php::Extension myExtension("my_extension", "1.0");
        myExtension.add<example1>("example1", { 
                Php::ByVal("curves", "Array", false); 
        });
        eturn myExtension;
    }
}

1 ответ

В отличие от вашего объявления Php::ByVal("кривые", "Массив", false); Я использую Php::ByVal("кривые", "Массив", правда);

Я не тестировал этот кусок кода, поэтому может потребоваться добавить небольшие исправления:-)

Удачи!

public:

  Php::Value GetAssociativeArray( Php::Parameters &params ) {

        if ( params.size( ) < 1 ) {
            error_function( "need at least 1 parameter" );        
        }

        if ( ! params[ 0 ].isObject( ) ) {
            error_function( "needs an object as first parameter" );
        }


        //
        // what you have to do before you can use this example:
        // define the data type data_t, which should be stored in php_array_result
        // supply the PHP class the objects in php_array_objects belong to -  can be coded in PHP or cpp
        // supply the PHP class the objects in php_array_result belong to -  can be coded in PHP or cpp
        //

        // the PHP object associated to the current cpp class
        Php::Value self( this );
        // the objects received
        Php::Value php_array_objects  = params[ 0 ];
        // the PHP array to return
        Php::Array php_array_result;
        // the c++ - class
        Curve * obj_curve;
        // a single PHP object from the PHP array we received
        Php::Value php_obj_in
        // a single object from the PHP array we are delivering
        Php::Object php_obj_out;
        // the key of the associative PHP Array
        std::string array_key;
        // the data to collect in the associative PHP array
        data_t data;        
        // some other data
        int64_t data_returned;


        for ( int i = 0; i < php_array_objects.size( ) ; i++ ) {

            // retrieve the next object
            php_obj_in = php_array_objects[ i ];

            // cast PHP object to c++-class
            obj_curve = ( Curve * ) php_obj_in.implementation( );

            // do something with obj_curve

            data = obj_curve->do_something( );

            // calculate the key

            key = "key_" + std::to_string( i );

            // to create an object pass in the class name ( Curve ) to the constructor with optional constructor parameters (1,2,3)

            php_obj_out = Php::Object( "Curve", 1, 2, 3 );

            // set a class member named "class_member" of php_obj_out

            php_obj_out[ "class_member" ] = data;

            // call the method "class_method" of php_obj_out

            data_returned = php_obj_out.call( "class_method", "parameter" );

            // add the new  created object to the PHP array

            php_array_result[ key ] = php_obj_out;

        }

        return php_array_result;

    }   // GetAssociativeArray( )    
Другие вопросы по тегам