Receive varying variable inputs from PHP into c++

一个人想着一个人 提交于 2019-12-01 10:58:26
m.s.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!