Python的C API不加载模块 [英] Python C API doesn't load module
问题描述
我试图加载包含在C数学和numpy的进口,使用C API的Python模块。我可以加载和运行模块,但如果我输入的数学模块,这是行不通的。
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.
我使用Arch Linux的,Python的2.7.2和gcc。
I'm using Arch Linux, Python 2.7.2 and gcc.
在这里,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
和我怎么能embbed Python脚本到C无需使用脚本?
And how can I embbed the Python script to C without need to use the script?
推荐答案
的 PySys_SetPath(。)
清除Python路径,因此它可能再也找不到任何库任何。你真正需要做的是进口sys.path中,然后你的字符串追加到它:
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("."));
(我没有测试上面的code,但它应该是接近。另外,你应该做的错误检查)
(I didn't test the above code, but it should be close. Also, you should do error checking)
这篇关于Python的C API不加载模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!