|
|
demo.py
- def add(a,b):
- print 'a=', a
- print 'b=', b
- return a + b
- print "hello world!"
复制代码
C语言代码:
- #include "stdio.h"
- #include "python.h"
- int PyCall( const char * module, const char * function, const char *format, ... )
- {
- PyObject* pMod = NULL;
- PyObject* pFunc = NULL;
- PyObject* pParm = NULL;
- PyObject* pRetVal = NULL;
- //导入模块
- if( !(pMod = PyImport_ImportModule(module) ) ){
- return -1;
- }
- //查找函数
- if( !(pFunc = PyObject_GetAttrString(pMod, function) ) ){
- return -2;
- }
- //创建参数
- va_list vargs;
- va_start( vargs, format );
- pParm = Py_VaBuildValue( format, vargs );
- va_end(vargs);
- //函数调用
- pRetVal = PyEval_CallObject( pFunc, pParm);
- int ret;
- PyArg_Parse( pRetVal, "i", &ret );
- return ret;
- }
- int main(int argc,char *argv[])
- {
- Py_Initialize();
- printf( "ret = %d\n", PyCall( "demo", "add", "(ii)", 99, 1));
- Py_Finalize();
- return 0;
- }
复制代码
执行结果:
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?注册
x
|