【发布时间】:2018-11-23 15:12:49
【问题描述】:
我见过Adding symbolic constants with hex values to Python extension module,我正在尝试重现这种效果:
#include <Python.h>
#include <Windows.h>
static PyObject * sys_shutdown(PyObject *self, PyObject *args) {
int val;
if (!PyArg_ParseTuple(args, "i", &val))
val = SHTDN_REASON_MINOR_OTHER; // Provide failsafe
ExitWindowsEx(EWX_POWEROFF, val); // Shutdown
return Py_BuildValue("");
}
static PyObject * sys_restart(PyObject *self, PyObject *args) {
int val;
if (!PyArg_ParseTuple(args, "i", &val))
val = SHTDN_REASON_MINOR_OTHER; // Provide failsafe
ExitWindowsEx(EWX_REBOOT, val); // Restart
return Py_BuildValue("");
}
static PyObject * sys_log_out(PyObject *self, PyObject *args) {
int val;
if (!PyArg_ParseTuple(args, "i", &val))
val = SHTDN_REASON_MINOR_OTHER; // Provide failsafe
ExitWindowsEx(EWX_LOGOFF, val); // Log out
return Py_BuildValue("");
}
static PyMethodDef localMethods[] = {
{"shutdown", (PyCFunction)sys_shutdown, METH_VARARGS, "..."},
{"restart", (PyCFunction)sys_restart, METH_VARARGS, "..."},
{"log_out", (PyCFunction)sys_log_out, METH_VARARGS, "..."},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef func = {
PyModuleDef_HEAD_INIT,
"utilities",
"...",
-1,
localMethods,
};
PyMODINIT_FUNC PyInit_utilities(void) {
PyObject *value;
value = PyModule_New(&func);
PyModule_AddIntConstant(value, "DEFINED", AF_INET);
return PyModule_Create(&func);
}
设置脚本:
from distutils.core import setup, Extension
module = Extension(
"utilities",
sources = ["main.c"],
libraries = ["user32"]
)
setup (
name = "Utilities",
version = "1.0",
ext_modules = [module])
一切都按预期构建,但是我不能在我的扩展中使用DEFINED:
import utilities
for i in utilities.__dict__: print(i)
utilities.DEFINED # AttributeError: module 'utilities' has no attribute 'DEFINED'
返回:
__name__
__doc__
__package__
__loader__
__spec__
shutdown
restart
log_out
__file__
我想像这样返回value:
return PyModule_Create(&value);
但是返回:
LINK : 致命错误 LNK1104: 无法打开文件 'build\lib.win32-3.6\WinUtils.cp36-win32.pyd' 错误:命令 'C:\Program Files (x86)\Microsoft Visual Studio\2017\WDExpress\VC\Tools\MSVC\14.14.26428\bin\HostX86\x86\link.exe' 失败,退出状态为 1104
如何将DEFINED 值添加到我的扩展程序(以便我可以运行utilities.DEFINED)?
编辑:
正如下面的答案中提到的,关闭所有内容并再次尝试成功构建扩展,但是使用return PyModule_Create(&value); 仍然崩溃。
【问题讨论】:
标签: python c python-3.x python-c-api