C语言调用PYTHON脚本

/*
#test.py

def py_func():
    print 'hello world. print from python'

def add(a,b):
    print 'add func called.'
    return a + b

if __name__ == '__main__':
    py_func()
*/

#include "stdafx.h"
#include "Python.h"
int _tmain(int argc, _TCHAR* argv[]){PyObject* pName = NULL;PyObject* pModule = NULL;PyObject* pDict = NULL;PyObject* pFunc = NULL;Py_Initialize();if(!Py_IsInitialized()){return -1;}const char *scriptDirectoryName = "."; PyObject *sysPath = PySys_GetObject("path"); PyObject *path = PyString_FromString(scriptDirectoryName); int result = PyList_Insert(sysPath, 0, path); pModule = PyImport_ImportModule("test");if(!pModule){printf("can't find call.py");getchar();return -1;}pDict = PyModule_GetDict(pModule);if(!pDict){return -1;}{pFunc = PyDict_GetItemString(pDict,"py_func");if(!pFunc || !PyCallable_Check(pFunc)){printf("can't find function [test]");getchar();return -1;}PyObject_CallObject(pFunc,0);}{pFunc = PyDict_GetItemString(pDict,"add");if(!pFunc || !PyCallable_Check(pFunc)){printf("can't find function [test]");getchar();return -1;}PyObject* args = PyTuple_New(2);PyTuple_SetItem(args,0,Py_BuildValue("l",3));PyTuple_SetItem(args,1,Py_BuildValue("l",4));PyObject *pAdded = PyObject_CallObject(pFunc,args);int ret = PyInt_AsLong(pAdded);printf("add value:%d\n", ret);Py_DECREF(args);}Py_DECREF(pName);Py_DECREF(pDict);Py_DECREF(pModule);Py_Finalize();return 0;}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值