Receive varying variable inputs from PHP into c++

后端 未结 1 537
悲&欢浪女
悲&欢浪女 2021-01-14 22:41

I have a program that needs to be sent the following variables:

Bool int string vector vector<

相关标签:
1条回答
  • 2021-01-14 22:46

    You can execute your C++ program in PHP using exec:

    exec("./your_program.exe $parameters", $output);
    

    This will pass the contents of $parameters as a command line argument to your C++ program. Within main(int argc, char** argv), you can then access this data through argc and argv.

    In order to pass multiple variables at once, you should use some kind of serialization. This will convert the contents of your variables into one single string which you can then pass again as a command line argument. You just have to make sure that the C++ side knows how to unserialize this string into the correct variables / datatypes again.

    There is a multitude of possibilities, ranging from inventing your own format (don't do this) to using one of the established ones (do this).

    Formats like JSON, XML, MessagePack, etc. come to mind. You could even implement something using PHP's own serialize method.


    To make things more clear, let's assume that you want to pass this data from PHP to C++:

    $var1 = false;
    $var2 = 123;
    $var3 = array("some","string","data");
    $var4 = "anotherstring";
    

    let's further assume you have a PHP function my_serialize() which converts array($var1, $var2, $var3, $var4) into the fictional serialization format false|123|<some,string,data>|anotherstring:

    $serialized_data = my_serialize(array($var1, $var2, $var3, $var4));
    // $serialized_data  == "false|123|<some,string,data>|anotherstring"
    
    // invoke your program and pass the data
    exec("./your_program.exe '$serialized_data'", $output);
    

    Within your program, the serialized data is now within argv[1]. You would now need a function my_deserialize() which parses the input data and converts them into the respective data format.

    int main(int argc, char** argv)
    {
        std::cout << argv[1] << std::endl;
        MyData data = my_deserialize(argv[1]);
        std::cout << data.var4 << std::endl; // outputs "another string"
    }
    

    Use one of the serialization methods I listed above and you don't have to care about the implementational details of my_serialize and my_deserialize.

    0 讨论(0)
提交回复
热议问题