如何传递价值和PHP运行C程序(Web应用程序) [英] How to pass value and run c program in php( web application)
问题描述
我有很大的 C
program.I想要在PHP执行该功能,并获得价值
I am having big c
program.I want execute that function in php and get value
例如
C程序
int add( int, int);
void main()
{
int i=1;
printf("i starts out life as %d.", i);
i = add(5, 10);
printf(" And becomes %d after function is executed.\n", i);
}
int add( int a, int b)
{
int c;
c = a + b;
return c;
}
我的网页形式都有价值a和b。所以,当我提交表单我想打电话给C函数添加和
得到的输出。
my web form has value a and b. so when i submit form i want to call the c function add and get the output.
我知道有执行在PHP外部程序功能
像
I know there is a function to execute external programs in php like
exec()
shell_exec()
但我不熟悉这个functions.so请给我code的样本。如果我把C程序文件(在记事本中)在服务器的根目录文件夹中。
But i am not familiar with this functions.so please give me sample of code. Should i place the c program file(in notepad) in server root folder.
请指导我!
在此先感谢
Please guide me ! Thanks in advance
推荐答案
我想最简单的方法是调用从PHP的C,传递
参数作为参数。在C面:
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;
}
(显然,你应该添加错误检查)。在PHP端:
(obviously, you should add error checking). On the PHP side:
$a = ...;
$b = ...;
$c = exec("/path/to/sum $a $b");
假设你的C程序被称为总和。
assuming your C program is called sum.
编辑:只要添加一个关于有各种办法评论
为您推荐至今:
Just adding a comment about the various approaches that have been suggested to you so far:
-
与
EXEC开始你的C程序()
,如上面我的回答是
真的是简单的解决方案。但是,它的成本你的创作
新的进程每次调用你的C code时,它可以是昂贵的
如果你这样做了很多。
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.
一个PHP扩展免去了进程创建和应多
高效,特别是如果你到C code使得许多电话和
你的C code是快速计算出结果。
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.
一个守护进程是比较有趣的,如果你的C程序慢启动
(长初始化),但随后快速处理查询。
A daemon is more interesting if your C program is slow to startup (long initialization) but can then process queries fast.
这篇关于如何传递价值和PHP运行C程序(Web应用程序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!