嵌入

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

C调用python中的函数:

hw.py:

#coding=utf8

def hw_hs(canshu):
    return canshu

if __name__  == "__main__":
    ccss = "I am hw"
    print hw_hs(ccss)

helloWorld.py:

#coding=utf8
import hw

def hello():
    ccss = "I am helloWorld"
    return hw.hw_hs(ccss)

if __name__  == "__main__":
    print hello()

testcpypy.c:

//#include "testcpypy.h"
#include <Python.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
    //初始化Python
    Py_Initialize();
    if (!Py_IsInitialized()) {
        printf("Py_Initialize");
        getchar();
        ;
    }      

    //执行python语句
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");

    PyObject *pModule = NULL;
    PyObject *pFunc = NULL;
    PyObject *reslt =NULL;

    //载入python模块
    if(!(pModule = PyImport_ImportModule("helloWorld"))) {
        printf("PyImport_ImportModule");
        getchar();
        ;
    }

    //查找函数
    pFunc = PyObject_GetAttrString(pModule, "hello");
    if ( !pFunc || !PyCallable_Check(pFunc) )
    {
        printf("can't find function [hello]");
        getchar();
        ;
    }

    //调用python中的函数
    reslt = (PyObject*)PyEval_CallObject(pFunc, NULL);
    //printf("function return value : %d\r\n", PyInt_AsLong(reslt));  

    //将python返回的对象转换为C的字符串
    char *resltc=NULL;
    int res;
    res = PyArg_Parse(reslt, "s", &resltc);
    if (!res) {
        printf("PyArg_Parse");
        getchar();
        ;
    }
    printf("resltc is %s", resltc);
    getchar();

    //释放内存
    Py_DECREF(reslt);
    Py_DECREF(pFunc);
    Py_DECREF(pModule);  

    //关闭python
    Py_Finalize();

    ;
}

编译:

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

执行结果:


带参数的情况:

#include "callpydll.h"
#include "Python.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

int callhello(char *instr, char *outstr)
{

    PyObject *pModule = NULL;
    PyObject *pFunc = NULL;
    PyObject *reslt = NULL;
    PyObject *pParm = NULL;

    char *resltc = NULL;
    int resltn;
    int res;

    char *helloWorld = "TestIM_ProtocBuf";

    char *im_account = "aaaa";
    char *auth_code = "aaaa";
    char *im_uid = "aaaa";
    char *proxy_topic = "";

    //初始化Python
    Py_Initialize();
    if (!Py_IsInitialized()) {
        printf("Py_Initialize");
        getchar();
        ;
    }      

    //执行python语句
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");

    //载入python模块
    if(!(pModule = PyImport_ImportModule(helloWorld))) {
        printf("PyImport_ImportModule");
        getchar();
        ;
    }

    //查找函数
    pFunc = PyObject_GetAttrString(pModule, "login_proxy_body_serialize");
    if ( !pFunc || !PyCallable_Check(pFunc) )
    {
        printf("can't find function [hello]");
        getchar();
        ;
    }

    //参数转换C --> python, 参数必须是元组(一个参数也是,否则会失败!!!坑啊)
    pParm = Py_BuildValue("(ssss)", im_account, auth_code, im_uid, proxy_topic);

    //调用python中的函数
    reslt = (PyObject*)PyEval_CallObject(pFunc, pParm);

    //将python返回的对象转换为C的字符串
    res = PyArg_ParseTuple(reslt, "si", &resltc, &resltn);
    if (!res) {
        printf("PyArg_Parse");
        getchar();
        ;
    }

    printf("resltn is %d", resltn);
    memcpy(outstr, resltc, strlen(resltc)+); 

    //释放内存
    Py_DECREF(reslt);
    Py_DECREF(pFunc);
    Py_DECREF(pModule);
    Py_DECREF(pParm);

    //关闭python
    Py_Finalize();

    ;
}

int main() {
    int i;
    char *dais = "iammain";
    ];
    memset(res,'\0',sizeof(res));

    i = callhello(dais, res);
     != i) {
        printf("Notify:error");
        getchar();
        ;
    }
    printf("result is %s", res);
    getchar();
    ;
}

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. Mysql数据库的使用总结之Innodb简介(一)

       最近在对开发的软件的服务器部分制作安装包,但服务器部分需要有mysql数据库的支持.因此,采用免安装版的mysql策略:将mysql数据库需要的文件在安装程序中进行设置和打包即可.但也遇到了很多 ...

  2. 【GoLang】golang 最佳实践汇总

    最佳实践 1 包管理 1.1 使用包管理对Golang项目进行管理,如:godep/vendor等工具 1.2 main/init函数使用,init函数参考python 1.2.1 main-> ...

  3. Python~迭代

            dict #默认情况下,dict迭代的是key 迭代value #迭代key,value     for value in  d.itervalues(): for k,v in d. ...

  4. Ubuntu设置环境变量 16.04

    打开终端并输入: sudo gedit /etc/environment. 2 输入用户密码.这时输入的密码是不可见的. 3 如图,在PATH="...."的末尾处添加: :/op ...

  5. 【原创】js中input type=file的一些问题

    1.介绍 在开发中,文件上传必不可少,input[type=file] 是常用的上传标签,但是它长得又丑.浏览的字样不能换,但是他长得到底有多丑呢.我们来看看在不同浏览器里的样子吧. <inpu ...

  6. MVC 前台获取三级菜单及子菜单

    1.在后台将所有的菜单获取出来,代码如下: public ActionResult Index() { //所有商品分类 var oneMenu = _baseGoodsCategory.FindLi ...

  7. 表格中每行的checkbox只能选中其中一个jquery实现

    HTML代码: <span class="number">12.</span> <div class="survey_txt mgl20&q ...

  8. 网络知识学习2---(IP地址、子网掩码)(学习还不深入,待完善)

    紧接着:网络知识学习1 1.IP地址    IP包头的结构如图 A.B.C网络类别的IP地址范围(图表) A.B.C不同的分配网络数和主机的方式(A是前8个IP地址代表网络,后24个代表主机:B是16 ...

  9. 开发常用之在webstorm中使用cmd

      而今前端开发经常与cmd打交道,如使用个npm什么的,如果老是在ide和cmd之间切换显得比较繁琐,众多前端利器中我最喜欢的就是webstorm,而webstorm中就可以直接使用cmd,如图1, ...

  10. include、merge 、ViewStub

    在布局优化中,Androi的官方提到了这三种布局<include />.<merge />.<ViewStub />,并介绍了这三种布局各有的优势,下面也是简单说一 ...