Python C API and C++ functions
Python C API and C++ functions
我正在尝试在我的C++程序中扩展Python解释器,我的问题如下。
当我尝试调用下面的代码中解释的函数时,我从 Python 解释器那里得到了一个NameError
。错误是
Traceback (most recent call last):
File "", line 3, in module
NameError: name 'func' is not defined
使用以下代码来绑定它,根据我在这里
使用的 Python 3.3.2 版的 Python wiki
double func( int a )
{
return a*a-0.5;
}
static PyObject *TestError;
static PyObject * func_test(PyObject * self, PyObject *args)
{
const int * command;
double sts;
if( !PyArg_ParseTuple(args, "i", &command) )
return NULL;
sts = func( *command );
return PyFloat_FromDouble(sts);
}
static PyMethodDef TestMethods[] = {
{"func", func_test, METH_VARARGS,
"Thing."},
{NULL, NULL, 0, NULL} /* Sentinel */
};
static struct PyModuleDef testmodule = {
PyModuleDef_HEAD_INIT,
"test", /* 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. */
TestMethods
};
PyMODINIT_FUNC PyInit_test()
{
PyObject *m;
m = PyModule_Create(&testmodule);
if (m == NULL)
return NULL;
TestError = PyErr_NewException("test.error", NULL, NULL);
Py_INCREF(TestError);
PyModule_AddObject(m, "error", TestError);
return m;
}
那我打电话给PyImport_AppendInittab("test", PyInit_test);
Py_Initialize();
,然后我正在尝试运行一个简单的测试,使用
PyRun_SimpleString("import testn"
"print('Hi!')n"
"b = func(5)n"
"print(b)n");
然而,我不断收到错误。有人可以解释一下,我在这里做错了什么吗?
PyRun_SimpleString("import testn"
"print('Hi!')n"
"b = test.func(5)n" # <--
"print(b)n");
编辑:另一个问题:
int command; // not "int *"
double sts;
if( !PyArg_ParseTuple(args, "i", &command) )
请注意,如果您还不熟悉如何编写CPython C扩展模块,我建议您使用CFFI。
我同意 Armin Rigo 的所有修复程序,我会添加这个:
PyImport_AppendInittab("test", &PyInit_test);
将函数的地址传递给 PyImport_AppendInittab
。
相关文章:
- 如何在Google Cloud Functions上运行C++文件?
- "thread-safe data"与"thread-safe code/functions"的区别
- 有没有办法扩展和调用 std::functions 的元组?
- C++ Functions & Arrays - Visual Studios 中的错误 C4700
- Protobuf 生成的C++类无法针对 iOS 进行编译,并显示错误"Only virtual member functions can be marked 'final'"
- StringCch* functions and Cstring
- Call std::functions
- "Default member initializer needed within definition of enclosing class outside of member functions
- TicTacToe C++ functions
- 创建带有任何参数的 std::functions 的unordered_map?
- 将lambdas/functions存储在std::vector中,而不使用std::function
- 如何让 CMake 编译包含 Boost Local Functions 的源文件
- "All arguments to functions are passed by value" C 中的,C++ 中对引用传递的混淆
- 犰狳/ Xcode:无处"functions that differ only in their return type cannot be overloaded"错误
- boost::bind with member functions(作为boost::asio异步写入处理程序)
- "functions"对话框过程中的过程
- "Only non-static member functions may be virtual"
- C++ "Virtual functions handling on multiple base classes"
- QML - Q_INVOKABLE functions
- "Cannot overload functions distinguished by return type alone"是什么意思?