PYTHON 与C相互交互调用实例解析

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值