Python嵌入成C - 导入模块 [英] Embedding Python into C - importing modules

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

问题描述

我在使用嵌入式的Python C作为按照文档问题 - 每当我尝试使用导入模块我得到一个:

I am having problems using the Embedded Python for C as per the Documentation - Whenever I try using imported modules I get an :

未处理的异常在PythonIncl.exe 0x1e089e85:0000005:
  访问冲突读取位置0x00000004。

Unhandled exception at 0x1e089e85 in PythonIncl.exe: 0xC0000005: Access violation reading location 0x00000004.

PyObject_GetAttrString()方法出现错误和文档没有太大的帮助。我也曾尝试使用教程作为在的例来自IBM 的,但总是得到相同的访问冲突。

The error occurs in the PyObject_GetAttrString() method and the documentation isn't much help. I have also tried using tutorials as in an Example from IBM, but always get the same access violation.

以下是教程的一个例子code,我似乎无法去上班,什么是错在这里?

The following is the example code from one of the tutorials which I can't seem to get to work, what is wrong here?

C- code(在一个主文件):

C-Code (in one main file):

#include <Python.h>
int main()
{
    PyObject *strret, *mymod, *strfunc, *strargs;
    char *cstrret;
    Py_Initialize();
    mymod = PyImport_ImportModule("reverse");
    strfunc = PyObject_GetAttrString(mymod, "rstring");
    strargs = Py_BuildValue("(s)", "Hello World");
    strret = PyEval_CallObject(strfunc, strargs);
    PyArg_Parse(strret, "s", &cstrret);
    printf("Reversed string: %s\n", cstrret);
    Py_Finalize();
    return 0;
}

Python的code(在一个名为reverse.py文件相同的文件夹):

Python code (in a file called reverse.py, same folder):

def rstring(s):
    i = len(s)-1
    t = ''
    while(i > -1):
        t += s[i]
        i -= 1
    return t

我正在使用MSVS2008一个XP的机器,Python 2.7版

I am running a XP machine using MSVS2008, Python 2.7

上下文的一点:我试图嵌入一个小python脚本,它使用OpenOPC,在一个相当大的C程序,并想在两者之间传输数据。不过,我已经不行了,证明了概念测试基本的例子。

A bit of context: I am trying to embed a small python script, which uses OpenOPC, in a fairly large C-program and would like to transfer data between the two. However I already fail at a proof-of-concept test with basic examples.

推荐答案

检查 PyImport_ImportModule 调用的结果:它失败,并返回 NULL 。这是因为在默认情况下,当前目录不在搜索路径。添加

Check the result of the PyImport_ImportModule call: It fails and returns NULL. That is because by default, the current directory is not in the search path. Add

PySys_SetPath("."); // before ..
mymod = PyImport_ImportModule("reverse");

当前目录添加到模块搜索路径,使您的工作,例如

to add the current directory to the module search path and make your example work.

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

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