gpt4 book ai didi

c++ - 在 Python 中调用 C++ 扩展

转载 作者:行者123 更新时间:2023-11-30 04:29:20 25 4
gpt4 key购买 nike

我正在尝试在 MSVC++ 2010 中使用 C++ 扩展 Python 3。我对这类事情完全陌生,而且我对 C++ 也不是很精通。根据我之前在这里收到的 python 文档和帮助,我编写了以下代码,它编译并成功运行:

#include <Python.h>
#include <iostream>
using namespace std;

static PyObject *SpamError;

static PyObject *spam_system(PyObject *self, PyObject *args)
{
const char *command;
int sts;

if (!PyArg_ParseTuple(args, "s", &command))
return NULL;
sts = system(command);
return PyLong_FromLong(sts);
}

static PyMethodDef SpamMethods[] = {
{"system", spam_system, METH_VARARGS,
"Execute a shell command."},
{NULL, NULL, 0, NULL} /* Sentinel */
};

static struct PyModuleDef spammodule = {
PyModuleDef_HEAD_INIT,
"spam", /* name of module */
NULL, /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. */
SpamMethods
};



PyMODINIT_FUNC
PyInit_spam(void)
{
PyObject *m;

m = PyModule_Create(&spammodule);
if (m == NULL)
return NULL;

SpamError = PyErr_NewException("spam.error", NULL, NULL);
Py_INCREF(SpamError);
PyModule_AddObject(m, "error", SpamError);
return m;
}

int main(int argc, wchar_t *argv[])
{
// Add a builtin module, before Py_Initialize
PyImport_AppendInittab("spam", PyInit_spam);

// Pass argv[0] to the Python Interpreter
Py_SetProgramName(argv[0]);

// Initialise the Python interpreter
Py_Initialize();

// Import module
PyImport_ImportModule("spam");

cout << "test" << endl;
system("PAUSE");
}

虽然我仍然不确定一些事情;我是否需要为此创建一个头文件,我应该如何去做?

此外,我最终打算如何通过 python shell 或在程序中调用扩展?

最佳答案

我已经使用 Boost Python 完成了这项工作。它构建一个 DLL 或共享对象(取决于平台是 Windows 还是 Linux)作为 Python 模块,然后您可以将其导入 Python 并像使用任何其他模块一样使用。它简单明了并且工作可靠。你已经有了你的 cpp 文件和头文件,所以你只需要编写包装器来公开你想从 Python 使用的函数/方法/类。我将包装器放在我的 cpp 文件的底部。它们看起来像这样:

#include <boost/python.hpp>

BOOST_PYTHON_MODULE(my_module)
{
boost::python::def("function_name", function, boost::python::args("start", "length", "offset", "boundry", "byte", "data", "variable" ), "docstring");
}

就是这样。

关于c++ - 在 Python 中调用 C++ 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9440789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com