c和python混编,c调用python模块中的函数

Tool ---> Option ---> Projectc and Solutions ---> VC++ Directories
在Include files加入python安装目录的include文件所在路径
在Libraray files加入python安装目录的libs文件夹所在路径

进入python的include目录,查找pyconfig。
ifdef _DEBUG
#    pragma comment(lib,"python27_d.lib")
#   else
#    pragma comment(lib,"python27.lib")
#   endif /* _DEBUG */
把python27_d.lib修改为python27.lib
之后保存即可。

#include <Python.h>
using namespace std;

void main()
{
	//这样也可以!!
	//system("test.py");

	//初始化python环境,为了之后使用python 提供的C API
	Py_Initialize();
	PyObject *pName,*pModule,*pFunc,*pArgs,*pValue;
	if (!Py_IsInitialized())
	{
		printf("Initialized Error! \n");
	}
	
	//最简易的python C API
	//PyRun_SimpleString("print 'hello world'");

	//得到python脚本的名字,并把这个模块引用进来,这个时候把模块主函数执行了!!
	pName = PyString_FromString("hello");
	pModule = PyImport_Import(pName);
	if (!pModule)
	{
		printf("can not open the script! \n");
	}

	//在引用的python模块中查找定义的函数
	pFunc = PyObject_GetAttrString(pModule,"hello");
	
	//第一种给函数参数赋值的方法
	/*pArgs = PyTuple_New(1);
	pValue = PyString_FromString("  10000");
	PyTuple_SetItem(pArgs,0,pValue);*/

	//第二种给函数参数赋值的方法
	pArgs = Py_BuildValue("(i)",10);

	//调用这个函数,第一个参数为返回的函数,第二个参数为函数参数列表
	PyObject_CallObject(pFunc,pArgs);
	//PyObject_CallObject(pFunc,NULL);

	//清理python环境
	Py_Finalize();

	//在这次写程序中遇到的问题就是:开始的时候c++工程名为test_project,
	//python脚本名称是test.py,所以在引用模块的时候错误地使用了其他文件
	//推测这个和python应用模块时候查找文件有关把,之后把脚本改名之后
	//就都可以了,弄了将近两个小时,很汗啊!
}

import os import sys def hello(a):     #print "hello world!"     print "execute the func"+str(a)     os.mkdir("test")    # system("mkdir test")

print "hello world" print "+++++++++++++++++++"

上面为hello.py


http://hi.baidu.com/zhengyl878/blog/item/bb1a9b3e6c2d97d37c1e713a.html这个网址有关于python C API的一些基本用法 

你可能感兴趣的:(c,python,脚本,System,import,include)