C调用Python函数相关代码示例剖析

  • C调用Python函数的相关操作将会在这篇文章中通过一段代码示例来为大 家详细介绍。初学者们可以通过这里介绍的内容充分掌握这一应用技巧。

我们在使用C语言的时候,有时会遇到需要调用Python 函数来完成一些特 定的功能。那么接下来,我们将会在这里为大家详细介绍一下C调用Python函数的相关操作方法,希望可以给大家带来一些帮助。

Python脚本,存为pytest.py

 
 
  1. def add(a,b):  

  2. print "in python function add"  

  3. print "
    a
     = " + str(a)  

  4. print "
    b
     = " + str(b)  

  5. print "
    ret
     = " + str(a+b)  

  6. return a + b 


C调用Python函数的代码示例:

 
 
  1. #include 
    <
     
    stdio.h
    >
     

  2. #include 
    <
     
    stdlib.h
    >
     

  3. #include "C:/Python26/include/python.h"  

  4. #pragma comment(lib, "C://Python26//libs//python26.lib")  

  5. int main(int argc, char** argv)  

  6. {  

  7. // 初始化Python  

  8. //在使用Python系统前,必须使用Py_Initialize对其  

  9. //进行初始化。它会载入Python的内建模块并添加系统路  

  10. //径到模块搜索路径中。这个函数没有返回值,检查系统  

  11. //是否初始化成功需要使用Py_IsInitialized。  

  12. PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pRetVal;  

  13. Py_Initialize();  

  14. // 检查初始化是否成功  

  15. if ( !Py_IsInitialized() )   

  16. {  

  17. return -1;  

  18. }  

  19. // 载入名为pytest的脚本(注意:不是pytest.py)  

  20. pName
     = 
    PyString_FromString
    ("pytest");  

  21. pModule
     = 
    PyImport_Import
    (pName);  

  22. if ( !pModule )  

  23. {  

  24. printf("can't find pytest.py");  

  25. getchar();  

  26. return -1;  

  27. }  

  28. pDict
     = 
    PyModule_GetDict
    (pModule);  

  29. if ( !pDict )   

  30. {  

  31. return -1;  

  32. }  

  33. // 找出函数名为add的函数  

  34. pFunc
     = 
    PyDict_GetItemString
    (pDict, "add");  

  35. if ( !pFunc || !PyCallable_Check(pFunc) )  

  36. {  

  37. printf("can't find function [add]");  

  38. getchar();  

  39. return -1;  

  40. }  

  41. // 参数进栈  

  42. pArgs
     = 
    PyTuple_New
    (2);  

  43. // PyObject* Py_BuildValue(char *format, ...)  

  44. // 把C++的变量转换成一个Python对象。当需要从  

  45. // C++传递变量到Python时,就会使用这个函数。此函数  

  46. // 有点类似C的printf,但格式不同。常用的格式有  

  47. // s 表示字符串,  

  48. // i 表示整型变量,  

  49. // f 表示浮点数,  

  50. // O 表示一个Python对象。  

  51. PyTuple_SetItem(pArgs, 0, Py_BuildValue("l",3));   

  52. PyTuple_SetItem(pArgs, 1, Py_BuildValue("l",4));  

  53. // 调用Python函数  

  54. pRetVal
     = 
    PyObject_CallObject
    (pFunc, pArgs);  

  55. printf("function return value : %ld/r/n", PyInt_AsLong(pRetVal));  

  56. Py_DECREF(pName);  

  57. Py_DECREF(pArgs);  

  58. Py_DECREF(pModule);  

  59. Py_DECREF(pRetVal);  

  60. // 关闭Python  

  61. Py_Finalize();  

  62. return 0;  

  63. }  

  64. //一下为个人实践的另一套方法  

  65. #include 
    <
     
    Python.h
    >
     

  66. #include 
    <
     
    conio.h
    >
     

  67. int main()  

  68. {  

  69. Py_Initialize();  

  70. if (!Py_IsInitialized())  

  71. {  

  72. printf("初始化错误/n");  

  73. return -1;  

  74. }  

  75. PyObject* 
    pModule
     = 
    NULL
    ;  

  76. PyObject* 
    pFunc
     = 
    NULL
    ;  

  77. PyObject* 
    pArg
     = 
    NULL
    ;  

  78. PyObject* 
    pRetVal
     = 
    NULL
    ;  

  79. pModule
     = 
    PyImport_ImportModule
    ("hello");  

  80. pFunc
     = 
    PyObject_GetAttrString
    (pModule,"hello");  

  81. pArg
     = 
    Py_BuildValue
    ("(i,i)",33,44);  

  82. pRetVal
     = 
    PyObject_CallObject
    (pFunc,pArg);  

  83. printf("%d/n",PyInt_AsLong(pRetVal));  

  84. Py_Finalize();  

  85. _getch();  

  86. return 0;  



以上就是我们对C调用Python函数的相关操作方法的介绍。

 

#include <Python.h>
#include <stdio.h>
void test( void )
{
    PyObject *pMod    = NULL;
    PyObject *pFun    = NULL;
    PyObject *pParm   = NULL;
    PyObject *pRetVal = NULL;
    int iRetval       = 0;
    if ( pMod = PyImport_ImportModule( "add" ) )
    {
        if ( pFun = PyObject_GetAttrString( pMod, "add" ) )
        {
            pParm = PyTuple_New( 2 );
            PyTuple_SetItem( pParm, 0, Py_BuildValue( "i", 300 ) );
            PyTuple_SetItem( pParm, 1, Py_BuildValue( "i", 500 ) );
            pRetVal = PyEval_CallObject( pFun, pParm );
            PyArg_Parse( pRetVal, "i", &iRetval );
            printf( "result: %d/n", iRetval );
        }
        else
            printf( "Not found fun!/n" );
    }
    else
        printf( "Not found module!/n" );
}
int main( void )
{
    Py_Initialize();
 &n ......

 

 

Ubuntu下首先要配置下环境;sudo apt-get install python-dev
以下是一个简单的例子:
#include "/usr/include/python2.5/Python.h"
#include <stdio.h>

int main(int arg,char **argv){
    PyObject *modelname,*model,*dict,*func,*args;
    char *name="os";//模块名
   
    //初始化Python
    Py_Initialize();
    if (!Py_IsInitialized()){
        printf("初始化失败/n");
        return -1;
    }
   
    //直接运行Python语句
    PyRun_SimpleString("print '初始化成功'");
   
    //导入Python模块
    modelname=PyString_FromString(name);
    model=PyImport_Import(modelname);
   
    if (model){
        printf("Load model ok/n");
    }
    else{
        printf("Model %s not found!/n",name);
        return -1;
    }
   
    dict=PyModule_GetDict(model);
   
    if(!dict){
        printf("获取字典失败/n");
        return -1;
    }
    else{
        printf("获取字典成功/n");   
    }
   
    //从模块中找到“System”函数
    func=PyDict_GetItemString(dict,"system");
   
    if(!func || !PyCallable_Check(func)){
        printf("函数无效/n");
        return -1;   
    }
   
    args=PyTuple_New(1);
   
    PyTuple_SetItem(args,0,Py_BuildValue("s","ls"));//l=long,s=string...
   
    //调用函数
    PyObject_CallObject(func,args);
   
    Py_DECREF(modelname);
    Py_DECREF(model);
    Py_DECREF(func);
    Py_DECREF(args);
    Py_DECREF(dict);
    //垃圾回收
    Py_Finalize();
    return 0;
}

下面就是编译连接生成可执行文件。
下面是用Python写的编译脚本。
#!/usr/bin/env python
import os
import sys

f=raw_input("C/C++ File:");
out=raw_input("Output file:");
sys.stdout.write("Trying to Complie C File using gcc.../n");
sys.stdout.write("---------------------------------------------------------/n");
if out=='' or out==None:
    os.system("gcc "+f +" -L/usr/lib/python2.5/config -lpython2.5 -lpthread -lm -ldl -lutil");
else:
    os.system("gcc "+f +" -L/usr/lib/python2.5/config -lpython2.5 -lpthread -lm -ldl -lutil "+"-o "+out);
   
sys.stdout.write("---------------------------------------------------------/n");
sys.stdout.write("Done!/n");

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值