免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1269 | 回复: 0
打印 上一主题 下一主题

PYTHON 与C相互交互调用实例解析(转载) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2005-11-29 03:17 |只看该作者 |倒序浏览

-----------------
http://www.54bk.com/more.asp?name=npng&id=19341
1、C中调用PYTHON
#include  
int main(int argc, char *argv[])
{
Py_Initialize();
PyRun_SimpleString("from time import time,ctime
"
"print 'Today is',ctime(time())
");
Py_Finalize();
return 0;
}
使用前工具:
Vc++编译器
Python 解释器
如没有装VC,可以去微软网站下一个C++的编译器,地址如下:
http://download.microsoft.com/download/3/9/b/39bac755-0a1e-4d0b-b72c-3a158b7444c4/VCToolkitSetup.exe
装完后,在环境变量中把PYTHON的INCLUDE和LIBS分别加入下面2个宏
INCLUDE
LIB
1、C中调用PYTHON
#include  
int main(int argc, char *argv[])
{
Py_Initialize();
PyRun_SimpleString("from time import time,ctime
"
"print 'Today is',ctime(time())
");
Py_Finalize();
return 0;
}
直接用CL 文件名  编译就是
2、用C生成DLL,用PYTHON调用
C代码:如FOO.C
#include
/* Define the method table. */
static PyObject *foo_bar(PyObject *self, PyObject *args);
static PyMethodDef FooMethods[] = {
{"bar",  foo_bar, METH_VARARGS},
{NULL, NULL}
};
/* Here's the initialization function.  We don't need to do anything
for our own needs, but Python needs that method table. */
void initfoo()
{
(void) Py_InitModule("foo", FooMethods);
}
/* Finally, let's do something ... involved ... as an example function. */
static PyObject *foo_bar(PyObject *self, PyObject *args)
{
char *string;
int   len;
if (!PyArg_ParseTuple(args, "s", &string))
return NULL;
len = strlen(string);
return Py_Buildvalue("i", len);
}
C定义文件:foo.def
EXPORTS
initfoo
编译生成foo.dll
Cl -c foo.c;
link foo.obj /dll /def:foo.def /OUT:foo.dll
在PYTHON中调用:
Import foo
Dir(foo)

即可以看到结果:
>>> import foo
>>> dir(foo)
['__doc__', '__file__', '__name__', 'bar']
>>> ^Z


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/8322/showart_59175.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP