Python嵌入C实例的相关具体解析

开发 后端
Python嵌入C的实际操作方案,你如果对其的具体的操作感兴趣的话,你就可以浏览以下的文章。对Python嵌入C这一操作有所了解。

Python在实际的相关应用中就有很强大功能,以及C在实际的运行中也具有很强的功能。如果对Python嵌入C你有过此想法的话,你就可以浏览我们的文章,其中包括中Python嵌入C的实例。望你会有所收获。

在VC++ 6.0中新建一个名为“EmbPython”的空“Win32 Console Application”工程。向其添加如下所示的“EmbPython.c”文件。

 

  1. #include <stdio.h> 
  2. #include <Python.h> 
  3. int main(int argc, char* argv[])  
  4. {   
  5. PyObject *modulename, *module, *dic, *func, *args, *rel, *list;  
  6. char *funcname1 = "sum";  
  7. char *funcname2 = "strsplit";  
  8. int i;  
  9. Py_ssize_t s;   

 

printf("-==在C中嵌入Python==-\n");/* Python解释器的初始化*/

 

  1. Py_Initialize();   
  2. if(!Py_IsInitialized())   
  3. {   
  4. printf("初始化失败!");   
  5. return -1;   
  6. }   

 

/* 导入Python模块,并检验是否正确导入 */

 

  1. modulename = Py_BuildValue("s", "pytest");   
  2. module = PyImport_Import(modulename);   
  3. if(!module)   
  4. {   
  5. printf("导入pytest失败!");   
  6. return -1;   
  7. }   

 

/* 获得模块中函数并检验其有效性 */

 

  1. dic = PyModule_GetDict(module);   
  2. if(!dic)  
  3. {  
  4. printf("错误!\n");  
  5. return -1;   
  6. }   

 

/* 获得sum函数地址并验证 */

 

  1. func = PyDict_GetItemString(dic,funcname1);   
  2. if(!PyCallable_Check(func))   
  3. {   
  4.  

 

printf("不能找到函数 %s",funcname1);

 

  1. return -1;   
  2. }  
  3.  

 

/* 构建列表 */

 

  1. list = PyList_New(5); 

printf("使用Python中的sum函数求解下列数之和\n");

 

  1. for (i = 0; i < 5; i++)  
  2. {  
  3. printf("%d\t",i);  
  4. PyList_SetItem(list,i,Py_BuildValue("i",i));  
  5. }  
  6. printf("\n");  
  7.  

 

/* 构建sum函数的参数元组*/

 以上就是对把Python嵌入C中的实例相关的内容的介绍,望你会有所收获。

【编辑推荐】

  1. 把Python嵌入C/C++模块与函数的实际操作步骤介绍
  2. 把Python嵌入C/C++模块与函数的操作步骤介绍
  3. 把Python嵌入C/C++元组操作的具体以应用方案介绍
  4. Python嵌入C/C++(较低层次嵌入)时所需用到的函数
  5. Python嵌入C/C++会产生的强大功能的介绍
责任编辑:佚名 来源: 博客园
相关推荐

2010-03-24 13:30:12

Python嵌入

2010-03-26 16:17:24

Python嵌入

2010-03-26 10:46:20

Python嵌入CC++

2010-03-24 10:06:37

Python嵌入C++

2009-09-09 14:40:15

C# XML解析

2009-08-27 17:40:21

C#接口的作用

2009-08-31 17:16:12

C#实现接口

2009-08-31 17:30:10

C#接口的作用

2009-08-28 15:37:22

C#线程类的定义

2009-09-09 13:57:28

C# XML解析

2009-08-18 10:47:40

C#枚举类型

2009-09-07 06:31:32

C#窗体移动

2009-08-26 12:14:44

C#打印设置

2009-08-31 18:17:32

C#接口编程

2009-08-19 16:09:15

C#操作Access

2009-09-04 16:55:09

C#DES算法解密

2010-02-01 16:40:14

C++枚举子

2010-02-02 16:15:38

C++变量声明

2009-12-03 17:05:40

Visual C++

2009-09-03 17:23:45

C#发送邮件
点赞
收藏

51CTO技术栈公众号