资讯专栏INFORMATION COLUMN

Embedding Python modules into C applications.

youkede / 2709人阅读

In official Doc. of Python 3, there is a short introduction to embedding Python in another application like C/C++ (seeEmbedding Python in Another Application).

The common procedure is as follows,

write prototype C/C++ code and Python module codes.
Note that in the Python codes conventions of python 2 & 3 can not be mixed together, which may cause segfault when running.

call.c

#include 

int
main(int argc, char *argv[])
{
    PyObject *pName, *pModule, *pDict, *pFunc;
    PyObject *pArgs, *pValue;
    int i;

    if (argc < 3) {
        fprintf(stderr,"Usage: call pythonfile funcname [args]
");
        return 1;
    }

    Py_Initialize();
    pName = PyUnicode_FromString(argv[1]);
    /* Error checking of pName left out */

    pModule = PyImport_Import(pName);
    Py_DECREF(pName);

    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, argv[2]);
        /* pFunc is a new reference */

        if (pFunc && PyCallable_Check(pFunc)) {
            pArgs = PyTuple_New(argc - 3);
            for (i = 0; i < argc - 3; ++i) {
                pValue = PyLong_FromLong(atoi(argv[i + 3]));
                if (!pValue) {
                    Py_DECREF(pArgs);
                    Py_DECREF(pModule);
                    fprintf(stderr, "Cannot convert argument
");
                    return 1;
                }
                /* pValue reference stolen here: */
                PyTuple_SetItem(pArgs, i, pValue);
            }
            pValue = PyObject_CallObject(pFunc, pArgs);
            Py_DECREF(pArgs);
            if (pValue != NULL) {
                printf("Result of call: %ld
", PyLong_AsLong(pValue));
                Py_DECREF(pValue);
            }
            else {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                PyErr_Print();
                fprintf(stderr,"Call failed
");
                return 1;
            }
        }
        else {
            if (PyErr_Occurred())
                PyErr_Print();
            fprintf(stderr, "Cannot find function "%s"
", argv[2]);
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        PyErr_Print();
        fprintf(stderr, "Failed to load "%s"
", argv[1]);
        return 1;
    }
    Py_Finalize();
    return 0;
}

multiply.py

def multiply(a,b):
    print("Will compute", a, "times", b)
    c = 0
    for i in range(0, a):
        c = c + b
    return c

For a single C code, just build like

g++ call.c -o call `python3-config --cflags` `python3-config --ldflags`

This can be written as a shell like build.sh.
3. To run the code, write a shell named run.sh,

PYTHONPATH=. ./call multiply multiply 3 2

Here call is the main code, the two multiplys are the module and function names, respectively.
When running, this code gives,

Will compute 3 times 2
Result of call: 6

Note if no PYTHONPATH=. statement in front of the run command, there will be errors like ImportError: No module named multiply.

Someone suggested to add into the .py file

import sys
sys.path.insert(0, "./path/to/your/modules/")

I tested but not helpful.
BTW, the system path can be checked by

import sys
print(sys.path)

Useful commands in Python 3 are:

PyObject *exc_type = NULL, *exc_value = NULL, *exc_tb = NULL;
PyErr_Fetch(&exc_type, &exc_value, &exc_tb);
PyObject* str_exc_type = PyObject_Repr(exc_type); //Now a unicode
object
PyObject* pyStr = PyUnicode_AsEncodedString(str_exc_type, "utf-8",
"Error ~");
const char *strExcType = PyBytes_AS_STRING(pyStr);
Py_XDECREF(str_exc_type);
Py_XDECREF(pyStr);

Py_XDECREF(exc_type);
Py_XDECREF(exc_value);
Py_XDECREF(exc_tb); 

Other useful tutorials are
Python嵌入C/C++ (Python核心编程)
C++中嵌入Python调用
Embedding Python in C/C++: Part I
Embedding Python in C/C++: Part II

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/45388.html

相关文章

  • Awesome Python II

    摘要: Caching Libraries for caching data. Beaker - A library for caching and sessions for use with web applications and stand-alone Python scripts and applications. dogpile.cache - dogpile.cache...

    lx1036 评论0 收藏0
  • Awesome Python

    摘要:漢字拼音 Awesome Python A curated list of awesome Python frameworks, libraries and software. Inspired by awesome-php. Awesome Python Environment Management Package Management Package Repositorie...

    fizz 评论0 收藏0
  • TensorFlow Wide And Deep 模型详解与应用

    摘要:我们先看看的初始化函数的完整定义,看构造一个模型可以输入哪些参数我们可以将类的构造函数中的参数分为以下几组基础参数我们训练的模型存放到指定的目录中。看完模型的构造函数后,我们大概知道和端的模型各对应什么样的模型,模型需要输入什么样的参数。 Wide and deep 模型是 TensorFlow 在 2016 年 6 月左右发布的一类用于分类和回归的模型,并应用到了 Google Play ...

    opengps 评论0 收藏0
  • NLP教程:教你如何自动生成对联

    摘要:本项目使用网络上收集的对联数据集地址作为训练数据,运用注意力机制网络完成了根据上联对下联的任务。这种方式在一定程度上降低了输出对位置的敏感性。而机制正是为了弥补这一缺陷而设计的。该类中有两个方法,分别在训练和预测时应用。 桃符早易朱红纸,杨柳轻摇翡翠群 ——FlyAI Couplets 体验对对联Demo: https://www.flyai.com/couplets s...

    Gu_Yan 评论0 收藏0
  • NLP教程:教你如何自动生成对联

    摘要:本项目使用网络上收集的对联数据集地址作为训练数据,运用注意力机制网络完成了根据上联对下联的任务。这种方式在一定程度上降低了输出对位置的敏感性。而机制正是为了弥补这一缺陷而设计的。该类中有两个方法,分别在训练和预测时应用。 桃符早易朱红纸,杨柳轻摇翡翠群 ——FlyAI Couplets 体验对对联Demo: https://www.flyai.com/couplets s...

    Dr_Noooo 评论0 收藏0

发表评论

0条评论

youkede

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<