【发布时间】:2021-09-24 20:52:04
【问题描述】:
在过去的几个小时里,我一直在尝试构建和运行一个简单的 c 模块,它会打印“hello world!!”。我遇到了一个我似乎无法解决的问题:
导入模块:
import hi
Traceback (most recent call last):
File "<ipython-input-1-746bfab23d87>", line 1, in <module>
import hi
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xae in position 2: invalid start byte
hellomodule.c:
#include <Python.h>
static PyObject *hello(void);
static PyMethodDef module_methods[] = {
{"hello", hello, METH_VARARGS},
{NULL, NULL, 0}
};
PyMODINIT_FUNC PyInit_hi(void)
{
PyObject *module;
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"hi",
module_methods,
NULL,
NULL,
NULL,
};
module = PyModule_Create(&moduledef);
return module;
}
static PyObject *hello(void)
{
printf("%s", "hello world");
return Py_BuildValue("Pls Work");
}
setup.py:
from distutils.core import setup, Extension
module1 = Extension('hi', sources=['hellomodule.c'])
setup(name='MyExtension',
version='1.0',
description='This is a demo extension',
ext_modules=[module1])
我要导入的实际模块显然是从“setup.py build”创建的.pyc。此代码适用于 windows 环境。任何帮助表示赞赏!谢谢!!
【问题讨论】:
标签: python c python-c-api