如何在不使用 ctype Linux 的情况下将 so 文件作为模块导入?
文件结构文件夹/home/cyan/TEMP
test.py
lib
|--libc_test_module.so
c_test_module.cc
CMakeLists.txt
test.py
import sys
sys.path.append("/home/cyan/TEMP/lib")
import c_test_module
c_test_module.cc
#include <Python.h>
int c_test_function(int a) {
return a + 1;
}
static PyObject * _c_test_function(PyObject *self, PyObject *args)
{
int _a;
int res;
if (!PyArg_ParseTuple(args, "i", &_a))
return NULL;
res = c_test_function(_a);
return PyLong_FromLong(res);
}
/* define functions in module */
static PyMethodDef TestMethods[] =
{
{"c_test_function", _c_test_function, METH_VARARGS,
"this is a c_test_function"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef c_test_module = {
PyModuleDef_HEAD_INIT,
"c_test_module", "Some documentation",
-1,
TestMethods
};
PyMODINIT_FUNC PyInit_c_test_module(void) {
PyObject *module;
module = PyModule_Create(&c_test_module);
if(module==NULL) return NULL;
/* IMPORTANT: this must be called */
import_array();
if (PyErr_Occurred()) return NULL;
return module;
}
错误
ModuleNotFoundError: No module named 'c_test_module'
问题
我不想使用ctype
模块导入.so
文件。相反,我想知道是否有办法直接将此文件作为模块导入。
File structure under folder /home/cyan/TEMP
test.py
lib
|--libc_test_module.so
c_test_module.cc
CMakeLists.txt
test.py
import sys
sys.path.append("/home/cyan/TEMP/lib")
import c_test_module
c_test_module.cc
#include <Python.h>
int c_test_function(int a) {
return a + 1;
}
static PyObject * _c_test_function(PyObject *self, PyObject *args)
{
int _a;
int res;
if (!PyArg_ParseTuple(args, "i", &_a))
return NULL;
res = c_test_function(_a);
return PyLong_FromLong(res);
}
/* define functions in module */
static PyMethodDef TestMethods[] =
{
{"c_test_function", _c_test_function, METH_VARARGS,
"this is a c_test_function"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef c_test_module = {
PyModuleDef_HEAD_INIT,
"c_test_module", "Some documentation",
-1,
TestMethods
};
PyMODINIT_FUNC PyInit_c_test_module(void) {
PyObject *module;
module = PyModule_Create(&c_test_module);
if(module==NULL) return NULL;
/* IMPORTANT: this must be called */
import_array();
if (PyErr_Occurred()) return NULL;
return module;
}
Error
ModuleNotFoundError: No module named 'c_test_module'
Question
I don't want to use ctype
module to import .so
file. Instead, I wonder if there is a way to import this file as a module directly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我创建了一个
setup.py
文件:现在可以导入
c_test_module
并调用函数。I created a
setup.py
file:Now it works to import
c_test_module
and call the functions.