How to pass value and run c program in php( web application)

前端 未结 2 510
小蘑菇
小蘑菇 2021-01-13 02:20

I am having big c program.I want execute that function in php and get value

For example

C program

int add( int, int);         
         


        
相关标签:
2条回答
  • 2021-01-13 02:55

    There's a way to do that - but it's not trivial by any means. You need to write a php extension in c/c++, install it on the server where the php will be executed and update you php.ini - and then you'll have access to the c/c++ functions directly from php. Have a look here: http://devzone.zend.com/article/1021 about how to write extensions.

    0 讨论(0)
  • 2021-01-13 02:56

    I guess the simplest way would be to call your C from PHP, passing the parameters as arguments. On the C side:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char *argv[])
    {
        int i = add(atoi(argv[1]), atoi(argv[2]));
        printf("%d\n", i);
        return 0;
    }
    

    (obviously, you should add error checking). On the PHP side:

    $a = ...;
    $b = ...;
    $c = exec("/path/to/sum $a $b");
    

    assuming your C program is called sum.


    Edit: Just adding a comment about the various approaches that have been suggested to you so far:

    • Starting your C program with exec(), as in my answer above, is really the simplest solution. However, it costs you the creation of a new process every time you call your C code, which can be expensive if you do it a lot.

    • A PHP extension spares the process creation and should be more efficient, especially if you are making many calls to your C code and your C code is fast to compute the result.

    • A daemon is more interesting if your C program is slow to startup (long initialization) but can then process queries fast.

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