Python C API doesn't load module

半腔热情 提交于 2019-11-26 23:26:44

问题


I'm trying to load a python module that contains a math and numpy import in C, using the C API. I can load and run the module but, if I import the math module it doesn't work.

I'm using Arch Linux, Python 2.7.2 and gcc.

Here the codes:

#include <stdio.h>
#include <stdlib.h>
#include <python2.7/Python.h>


int main(int argc, char **argv)
{
    PyObject *pName, *pModule, *pFunc, *pArg, *pDict, *pReturn, *pT1, *pT2, *pX, *pY;
    int i;
    double x, y;

    Py_Initialize();

    PySys_SetPath(".");

    pName = PyString_FromString("func");
    if (!pName)
    {
        printf("pName\n");
        return 0;
    }
    pModule = PyImport_Import(pName);

    pDict = PyModule_GetDict(pModule);
    pFunc = PyDict_GetItemString(pDict, "get_vals");
    pArg = PyTuple_New(2);
    PyTuple_SetItem(pArg, 0, PyFloat_FromDouble(4.0));
    PyTuple_SetItem(pArg, 1, PyFloat_FromDouble(2.0));
    pReturn = PyObject_CallObject(pFunc, pArg);
    pT1 = PyTuple_GetItem(pReturn, 0);
    pT2 = PyTuple_GetItem(pReturn, 1);

    for (i = 0; i < PyTuple_Size(pT1); i++)
    {
        pX = PyTuple_GetItem(pT1, i);
        pY = PyTuple_GetItem(pT2, i);
        x = PyFloat_AsDouble(pX);
        y = PyFloat_AsDouble(pY);
        Py_XDECREF(pX);
        Py_XDECREF(pY);
        pX = NULL;
        pY = NULL;
        printf("Point p position is: %.2fx, %.2fy", x, y);
    }

    Py_XDECREF(pName); Py_XDECREF(pModule); Py_XDECREF(pFunc); Py_XDECREF(pArg); Py_XDECREF(pDict); Py_XDECREF(pReturn); Py_XDECREF(pT1); Py_XDECREF(pT2);

    Py_Finalize();

    return 0;
}

func.py

from math import cos

def get_vals(width, height):
    x = (1, 2)
    y = (cos(3), 4)

    return x, y

And how can I embbed the Python script to C without need to use the script?


回答1:


The PySys_SetPath(".") cleared the python path, so it could no longer find any library whatsoever. What you really need to do is import sys.path and then append your string to it:

PyObject *sys = PyImport_ImportModule("sys");
PyObject *path = PyObject_GetAttrString(sys, "path");
PyList_Append(path, PyString_FromString("."));

(I didn't test the above code, but it should be close. Also, you should do error checking)



来源:https://stackoverflow.com/questions/7624529/python-c-api-doesnt-load-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!