嵌入

与python的扩展相对,嵌入是把Python解释器包装到C的程序中。这样做可以给大型的,单一的,要求严格的,私有的并且(或者)极其重要的应用程序内嵌Python解释器的能力。一旦内嵌了Python,世界完全不一样了。

C调用python中的函数:

hw.py:

  1. #coding=utf8
  2.  
  3. def hw_hs(canshu):
  4. return canshu
  5.  
  6. if __name__ == "__main__":
  7. ccss = "I am hw"
  8. print hw_hs(ccss)

helloWorld.py:

  1. #coding=utf8
  2. import hw
  3.  
  4. def hello():
  5. ccss = "I am helloWorld"
  6. return hw.hw_hs(ccss)
  7.  
  8. if __name__ == "__main__":
  9. print hello()

testcpypy.c:

  1. //#include "testcpypy.h"
  2. #include <Python.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5.  
  6. int main()
  7. {
  8. //初始化Python
  9. Py_Initialize();
  10. if (!Py_IsInitialized()) {
  11. printf("Py_Initialize");
  12. getchar();
  13. ;
  14. }
  15.  
  16. //执行python语句
  17. PyRun_SimpleString("import sys");
  18. PyRun_SimpleString("sys.path.append('./')");
  19.  
  20. PyObject *pModule = NULL;
  21. PyObject *pFunc = NULL;
  22. PyObject *reslt =NULL;
  23.  
  24. //载入python模块
  25. if(!(pModule = PyImport_ImportModule("helloWorld"))) {
  26. printf("PyImport_ImportModule");
  27. getchar();
  28. ;
  29. }
  30.  
  31. //查找函数
  32. pFunc = PyObject_GetAttrString(pModule, "hello");
  33. if ( !pFunc || !PyCallable_Check(pFunc) )
  34. {
  35. printf("can't find function [hello]");
  36. getchar();
  37. ;
  38. }
  39.  
  40. //调用python中的函数
  41. reslt = (PyObject*)PyEval_CallObject(pFunc, NULL);
  42. //printf("function return value : %d\r\n", PyInt_AsLong(reslt));
  43.  
  44. //将python返回的对象转换为C的字符串
  45. char *resltc=NULL;
  46. int res;
  47. res = PyArg_Parse(reslt, "s", &resltc);
  48. if (!res) {
  49. printf("PyArg_Parse");
  50. getchar();
  51. ;
  52. }
  53. printf("resltc is %s", resltc);
  54. getchar();
  55.  
  56. //释放内存
  57. Py_DECREF(reslt);
  58. Py_DECREF(pFunc);
  59. Py_DECREF(pModule);
  60.  
  61. //关闭python
  62. Py_Finalize();
  63.  
  64. ;
  65. }

编译:

gcc -o testcpypy testcpypy.c  -IC:\Python27\include -LC:\Python27\libs -lpython27    ---C:\Python27为python安装目录

或:
gcc -c testcpypy.c -IC:\Python27\include
gcc -o testcpypy.exe testcpypy.o -LC:\Python27\libs -lpython27

执行结果:


带参数的情况:

  1. #include "callpydll.h"
  2. #include "Python.h"
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <stdarg.h>
  7.  
  8. int callhello(char *instr, char *outstr)
  9. {
  10.  
  11. PyObject *pModule = NULL;
  12. PyObject *pFunc = NULL;
  13. PyObject *reslt = NULL;
  14. PyObject *pParm = NULL;
  15.  
  16. char *resltc = NULL;
  17. int resltn;
  18. int res;
  19.  
  20. char *helloWorld = "TestIM_ProtocBuf";
  21.  
  22. char *im_account = "aaaa";
  23. char *auth_code = "aaaa";
  24. char *im_uid = "aaaa";
  25. char *proxy_topic = "";
  26.  
  27. //初始化Python
  28. Py_Initialize();
  29. if (!Py_IsInitialized()) {
  30. printf("Py_Initialize");
  31. getchar();
  32. ;
  33. }
  34.  
  35. //执行python语句
  36. PyRun_SimpleString("import sys");
  37. PyRun_SimpleString("sys.path.append('./')");
  38.  
  39. //载入python模块
  40. if(!(pModule = PyImport_ImportModule(helloWorld))) {
  41. printf("PyImport_ImportModule");
  42. getchar();
  43. ;
  44. }
  45.  
  46. //查找函数
  47. pFunc = PyObject_GetAttrString(pModule, "login_proxy_body_serialize");
  48. if ( !pFunc || !PyCallable_Check(pFunc) )
  49. {
  50. printf("can't find function [hello]");
  51. getchar();
  52. ;
  53. }
  54.  
  55. //参数转换C --> python, 参数必须是元组(一个参数也是,否则会失败!!!坑啊)
  56. pParm = Py_BuildValue("(ssss)", im_account, auth_code, im_uid, proxy_topic);
  57.  
  58. //调用python中的函数
  59. reslt = (PyObject*)PyEval_CallObject(pFunc, pParm);
  60.  
  61. //将python返回的对象转换为C的字符串
  62. res = PyArg_ParseTuple(reslt, "si", &resltc, &resltn);
  63. if (!res) {
  64. printf("PyArg_Parse");
  65. getchar();
  66. ;
  67. }
  68.  
  69. printf("resltn is %d", resltn);
  70. memcpy(outstr, resltc, strlen(resltc)+);
  71.  
  72. //释放内存
  73. Py_DECREF(reslt);
  74. Py_DECREF(pFunc);
  75. Py_DECREF(pModule);
  76. Py_DECREF(pParm);
  77.  
  78. //关闭python
  79. Py_Finalize();
  80.  
  81. ;
  82. }
  83.  
  84. int main() {
  85. int i;
  86. char *dais = "iammain";
  87. ];
  88. memset(res,'\0',sizeof(res));
  89.  
  90. i = callhello(dais, res);
  91. != i) {
  92. printf("Notify:error");
  93. getchar();
  94. ;
  95. }
  96. printf("result is %s", res);
  97. getchar();
  98. ;
  99. }

C中嵌入python的更多相关文章

  1. 在应用中嵌入Python:转

    在应用中嵌入Python 前面的章节讨论如何扩展Python,如何生成适合的C库等.不过还有另一种情况:通过将Python嵌入C/C++应用以扩展程序的功能.Python嵌入实现了一些使用Python ...

  2. c++中嵌入python

    c++ 中嵌入python  :  https://blog.csdn.net/yiyouxian/article/category/6324494 Python C 和线程 :http://www. ...

  3. 【转】C++中嵌入python程序——参数传递

    C++中嵌入python程序——参数传递 前面两篇博客已经介绍如何在C++中嵌套使用 python,但是在实际使用中,我们需要向python传递各种各样的参数,这样的程序才具有更高的灵活性.下面简单介 ...

  4. 如何在 Go 中嵌入 Python

    如果你看一下 新的 Datadog Agent,你可能会注意到大部分代码库是用 Go 编写的,尽管我们用来收集指标的检查仍然是用 Python 编写的.这大概是因为 Datadog Agent 是一个 ...

  5. 在 C 代码中嵌入 Python 语句或使用 Python 模块 (Visual Studio 2013 环境设置)

    1) 新建一个 内嵌 Python 语句的 C 代码, // This is a test for check insert the Python statements or module in C. ...

  6. 如何在batch脚本中嵌入python代码

    老板叫我帮他测一个命令在windows下消耗的时间,因为没有装windows那个啥工具包,没有timeit那个命令,于是想自己写一个,原理很简单: REM timeit.bat echo %TIME% ...

  7. C++中嵌入python程序——命令行模式

    http://blog.csdn.net/yiyouxian/article/details/51992721

  8. 嵌入Python | 调用Python模块中有参数的函数

    开发环境Python版本:3.6.4 (32-bit)编辑器:Visual Studio CodeC++环境:Visual Studio 2013 需求说明前一篇<在C++中嵌入Python|调 ...

  9. 在C语言中如何嵌入python脚本

    最近在写配置文件时,需要使用python脚本,但脚本是一个监控作用,需要它一直驻留在linux中运行,想起C语言中能够使用deamon函数来保留一个程序一直运行,于是想到写一个deamon,并在其中嵌 ...

随机推荐

  1. 委托 与 Lambda

    一.委托调用方式 1. 最原始版本: delegate string PlusStringHandle(string x, string y); class Program { static void ...

  2. screen 常用命令

    screen -r <id | name>  # 进入 screen C-a c # ctrl+a + c , 新建screen窗口 C-a A # ctrl+a + A, 命名scree ...

  3. linuxqq

    centos7下安装linuxqq出现一大堆依赖包都没有,腾讯搞的这个产品真不给力.寒心. >>>以下来自百度知道:http://zhidao.baidu.com/question/ ...

  4. placeholer 换行

    如果需要placeholder 换行: 代码: <textarea class="desc_content"maxlength="50" placehol ...

  5. UIImage加载本地图片的两种方式

    UIImage加载图片方式一般有两种: (1)imagedNamed初始化:默认加载图片成功后会内存中缓存图片,这个方法用一个指定的名字在系统缓存中查找并返回一个图片对象.如果缓存中没有找到相应的图片 ...

  6. Git学习总结

    master主分支合并dev分支,代码 :git merge dev ,跳出如下界面.输入:wq,(:wq命令是LINUX命令,强制写入文件并结束),可以强制合并.但为什么会跳出该界面,我也没搞清楚. ...

  7. 打开APK里的AndroidManifest.xml乱码

    直接解压apk,打开AndroidManifest.xml显示乱码,因为这里面是二进制字符,和打开文件的编辑器无关.(也可以用ultraedit打开查看,有明文显示.只是看起来搜起来不是很方便而已) ...

  8. ORACLE用户创建&删除

    ●sqlplus登陆sqlplus sys/isc@testgmmc as sysdba●创建用户create user testpoi3 IDENTIFIED by iscaccount unloc ...

  9. 《图形学》实验六:中点Bresenham算法画圆

    开发环境: VC++6.0,OpenGL 实验内容: 使用中点Bresenham算法画圆. 实验结果: 代码: #include <gl/glut.h> #define WIDTH 500 ...

  10. [LeetCode] Best Time to Buy and Sell Stock

    Say you have an array for which the ith element is the price of a given stock on day i. If you were ...