简单配置如下:
python安装目录: C:\Python26
头文件包含:
VStudio->Tools->Options->Directories->Include files 加入 C:\PYTHON26\INCLUDE
库文件包含:
VStudio->Tools->options->Directories->Library files 加入 C:\PYTHON26\LIBS
如果是debug版本,有可能会提示can't open file "python26_d.lib"没有调试版本的类库.
Solution: 把C:\Python26\libs\python26.lib复制一个python26_d.lib即可
否则直接用release版本就行; Or change python26_d.lib to python26.lib in "pyconfig.h" file, and comment "#define Py_DEBUG".
工程文件中包含了c++调用python中的函数,也同时把c++的函数做成了dll,以供python之调用;
Py_Finalize(); 以至于python又调用dll时,发生错误;所以在生成dll时,注释掉
Py_Initialize();以及Py_Finalize();
若没有装VC,可以去微软网站下一个C++的编译器 VCTookitSetup.exe.
Under VC->VStudio Tools-> VStudio 2005 command prompt , 执行命令 cl cfile编译。
举例:
1、C中调用PYTHON
#include
int main(int argc, char *argv[])
{
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print 'Today is',ctime(time())\n");
Py_Finalize();
return 0;
}
直接用CL 文件名 编译就是
2、
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
将foo.dll 改名为 foo.pyd
在PYTHON中调用:
import foo
dir(foo)
…
即可以看到结果:
>>> import foo
>>> dir(foo)
['__doc__', '__file__', '__name__', 'bar']
>>> ^Z
3 C调用由python生成的dll
写一个C程序,该程序存放调用python的函数接口。然后将该C程序和python程序一起做成DLL即可。
主要参考
没有评论:
发表评论