Python嵌入 [英] embedding python

查看:279
本文介绍了Python嵌入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着从C code调用Python函数,我跟着从的此处

Im trying to call python functions from C code, and i followed a sample from here

我也有正确的包含文件directries,图书馆directries和链接的python32.lib(使用python 32 IM),但是错误是,蟒蛇/ C API,如PyString_FromString,PyInt_FromLong,PyInt_AsLong是不确定的(在调试器错误)

I also have the correct include file directries, library directries, and linked the python32.lib (im using python 32) however the error was that python/C APIs such as PyString_FromString, PyInt_FromLong, PyInt_AsLong are undefined (error in the debugger)

这很奇怪,因为IM也在使用其他的API,但他们都很好...

this is strange because im also using other APIs, but they're all fine...

什么问题就在这里?

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]\n");
        return 1;
    }

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

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

    if (pModule != NULL) {
        pDict = PyModule_GetDict(pModule);
        /* pDict is a borrowed reference */

Py_Initialize(),PyImport_Import(),PyModule_GetDict()所有工作正常,但不是PyString_FromString ...

Py_Initialize(), PyImport_Import(), PyModule_GetDict() all work fine, but not PyString_FromString...

推荐答案

这个例子code你采用的是古Python版本,2.3.2。 Python 3.x都有线不仅在语言但C API中也是如此。

The example code you used is for ancient Python version, 2.3.2. Python 3.x line introduced a number of incompatibilites not only in the language but in the C API as well.

您只需提在Python 3.2不复存在功能

The functions you mention simply no longer exist in Python 3.2.

PyString _ 函数被重命名为 PyBytes _

PyInt _ 功能都走了, PyLong _ 应改为使用。

PyInt_ functions are gone, PyLong_ should be used instead.

下面是相同的例子,你已经使用,但对于Python 3:

Here's the same example that you've used but for Python 3:

5.3。纯嵌入

请注意,它的使用 PyUni code _ 而不是 PyString_ / PyBytes _ 。在许多地方的Python 2.x的使用字节串,Python 3.x都有使用UNI code字符串。

Note that it's using PyUnicode_ instead of PyString_/PyBytes_. In many places where Python 2.x used byte strings, Python 3.x uses unicode strings.

顺便说一句,我通常使用此页面来查找所有可能的呼叫:

By the way, I usually use this page to look up all possible calls:

指数 - P

这篇关于Python嵌入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆