我很难在代码中将C扩展作为子模块。下面的C扩展编译得很好。当我尝试将其添加到另一个模块时,就会出现问题。
这是C代码:文件名是prctl3-0。c、 我能够为两个Python2编译它。7和Python 3.0。
#include <Python.h>
#include <stdio.h>
#include <string.h>
#include <sys/prctl.h>
#if PY_MAJOR_VERSION >=3
#define PY_3CODE
#endif
static PyObject* osCall_changeName(PyObject*self, PyObject* args)
{
const char *passedInName;
size_t nameLength;
char newName[16];
int nameChangeRes;
PyObject *retName;
if(! PyArg_ParseTuple(args, "s", &passedInName)){
printf("Error in arg passing\n");
Py_RETURN_NONE;
}
nameLength = strlen(passedInName);
if( nameLength > 15){
strncpy(newName, passedInName, 15);
newName[15] = '\0';
} else {
strcpy(newName, passedInName);
}
nameChangeRes = prctl(PR_SET_NAME, newName, 0,0,0);
if( nameChangeRes == 0 )
{
retName = Py_BuildValue("s", newName);
return retName;
}
Py_RETURN_NONE;
}
static PyObject* osCall_getName(PyObject* self) {
char procName[16];
int nameRetrieveRes;
PyObject *retName;
nameRetrieveRes = prctl(PR_GET_NAME, procName, 0,0,0);
if ( nameRetrieveRes == 0 )
{
retName = Py_BuildValue("s", procName);
return retName;
}
printf("Process name change failed\n");
Py_RETURN_NONE;
}
static PyMethodDef proc_OsFunc[] = {
{ "changeName",
(PyCFunction)osCall_changeName,
METH_VARARGS,
"Function to give Python process a new associated string ID"},
{ "getName",
(PyCFunction)osCall_getName,
METH_NOARGS,
"Function to get Python process's current string ID"
},
{NULL, NULL, 0, NULL}
};
#ifdef PY_3CODE
static struct PyModuleDef osCallDefine = {
PyModuleDef_HEAD_INIT,
"prctl3_0",
"A simple library for accessing prctl() on Linux from Python 3.0",
-1,
proc_OsFunc
};
#endif
#ifdef PY_3CODE
PyMODINIT_FUNC PyInit_prctl3_0(void)
{
Py_Initialize();
return PyModule_Create(&osCallDefine);
}
#else
PyMODINIT_FUNC initprctl3_0() {
Py_InitModule3("prctl3_0",proc_OsFunc,
"A simple library for accessing prctl() on Linux from Python 2.0");
}
#endif
我希望在模块名称中包含此代码
mpIPC
作为更大项目的一部分。我遇到的问题是,当我将其放入一个更大的模块中,并尝试使用以下代码访问它时,我得到以下结果:
>>> import mpIPC.prctl3_0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named prctl3_0
我的
setup.py
文件如下:
from setuptools import setup, find_packages, Extension
prctl_module = Extension("mpIPC.prctl3_0",
sources = ["mpIPC/prctl3_0.c"])
setup(name = "mpIPC",
version = '0.0',
description = "Python C module for accessing Linux commands for IPC",
packages = ['mpIPC'],
ext_modules = [prctl_module] )
此模块的我的文件目录:
project/
+- setup.py
+- mkdir/
-+- __init__.py
-+- prctl3_0.c
-+- os.py # used for other Linux os calls
我不确定我错过了什么。我还检查了以下链接:
How to build a Python C Extension so I can import it from a module
但在这一点上,它并没有真正帮助我。