简体   繁体   中英

How do I get the return value of a c++ function in php code?

It's a beginner question but I researched a lot and barely found anything. Many articles or examples on zend don't exist anymore and I cant really make progress so bare with me. I'd like to get the result from an existing c++ function to use it in php code. I set up a super simple example: My c++ code looks like the following for now:

#include<iostream>
int returnnumber() {

    return 4 + 2;
}

int main() {

    
    std::cout << "test";
    return 0;
}

and my php code looks like this:

<html>
    <head>
        <title>PHP-Test</title>
    </head>
    <body>
        
        <?php 
        $filename = "pathtofile";
        
        if (file_exists($filename)) {
                echo "the file exists, ";
        } else {
             echo "The file doesnt exist";
        }
        $output = 0;
        $output = shell_exec($filename);
        //$output = 2
        echo $output; ?>
    </body>
</html>

The output for this is the file exists, test However, when I remove the comments of $output = 2 the result becomes the file exists, 2 which I really don't understand. Why is $output my cout string value and not my return integer value from my main function, so 0 in this case? And how do I get the value 0, and additionally,how would I get the result of,in this case, int returnnumber() ?

You can try this:

<?php
$out = shell_exec("date > /dev/null 2>&1; echo $?");
echo "result is: $out";
 ?>

This is how we get exit status of any command in shell. You execute the command and check the value of $? (and probably divide it by 256 but not in this case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM