【发布时间】:2017-08-14 18:23:40
【问题描述】:
我正在尝试导入与 main.c 文件位于同一目录中的 python 文件,但由于某种原因它无法正常工作。我在 PyImport_ImportModule('dizzle') 上一直失败。任何帮助将不胜感激我在 Mac 上(*我可以让它在 Ubuntu 上工作,这很奇怪)我设置了 PYTHONPATH。
mytestfolder
main.c
dizzle.py
这是我的 main.c
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <Python/Python.h>
int main()
{
char *xx = getpimacaddress2();
printf("%s", xx);
}
char *getpimacaddress2()
{
Py_Initialize();
PyObject* module = PyImport_ImportModule("dizzle");
assert(module != NULL);
PyObject* klass = PyObject_GetAttrString(module, "SnowTest");
assert(klass != NULL);
PyObject* instance = PyInstance_New(klass, NULL, NULL);
assert(instance != NULL);
PyObject* result = PyObject_CallMethod(instance, "add_test", "(ii)", 10, 34);
assert(result != NULL);
Py_Finalize();
return PyString_AsString(result);
}
Python 文件dizzle.py
class SnowTest:
def add_test(self, x, y):
z = x + y
return str(z)
【问题讨论】:
-
怎么会失败?
-
在我的第一个断言中,我认为这是由于它没有在当前目录中找到我的模块@Vallentin
-
您记得将路径
PyObject *path = PyObject_GetAttrString(PyImport_ImportModule("sys"), "path")和PyList_Append(path, ...)取为您应用程序的当前工作目录吗? -
检查是否设置了异常(如果有)
if(PyErr_Occurred()) PyErr_Print(); -
我尝试了你的建议,但我仍然收到断言失败:(module != NULL) @Vallentin
标签: python c python-2.7