Python:传递 c++对象到脚本,然后调用扩展 c++脚本中的函数
首先,问题是程序因双重内存释放而失败......
处理是: 我已经
FooCPlusPlus *obj;
并将其传递给我的脚本。效果很好。像这样:
PyObject *pArgs, *pValue;
pArgs = Py_BuildValue("((O))", obj);
pValue = PyObject_CallObject(pFunc, pArgs);
其中 pFunc 是一个 python 函数...... 所以,我的脚本具有函数,我在其中使用 obj.
def main(args)
...
pythonObj = FooPython(args[0])
...
# hardcore calculation of "x"
...
...
pythonObj.doWork(x)
当然,我已经定义了Python类
class FooPython:
def __init__(self, data):
self._base = data
def doWork(arg):
import extend_module
extend_module.bar(self._base, arg)
“Extend_module”是一个扩展C++模块,我在其中定义了函数“bar”。
我预计“bar”函数会正常工作,但我却得到了内存错误:“双内存空闲或损坏”。
这是“bar”函数:
static PyObject* bar(PyObject *self, PyObject *args)
{
PyObject *pyFooObject = 0;
int arg;
int ok = PyArg_ParseTuple(args,"Oi",&pyRuleHandler, &arg);
if(!ok) return 0;
void * temp = PyCObject_AsVoidPtr(pyFooObject);
FooCPlusPlus* obj = static_cast<FooCPlusPlus*>(temp);
obj->method(arg); // some c++ method
return PyCObject_FromVoidPtr((void *) ruleHandler, NULL);
}
它在“bar”的 return 语句处失败......
First of all, the problem is that program fails with double memory freeing ...
The deal is:
I have
FooCPlusPlus *obj;
and I pass it to my script. It works fine. Like this:
PyObject *pArgs, *pValue;
pArgs = Py_BuildValue("((O))", obj);
pValue = PyObject_CallObject(pFunc, pArgs);
where pFunc is a python function...
So, my script has function, where I use obj.
def main(args)
...
pythonObj = FooPython(args[0])
...
# hardcore calculation of "x"
...
...
pythonObj.doWork(x)
Of course I've defined python class
class FooPython:
def __init__(self, data):
self._base = data
def doWork(arg):
import extend_module
extend_module.bar(self._base, arg)
"Extend_module" is an extension c++ module where I've defined function "bar".
I expected that "bar" function would work fine, but instead of it I got memory errors: "double memory free or corruption".
Here is "bar" function:
static PyObject* bar(PyObject *self, PyObject *args)
{
PyObject *pyFooObject = 0;
int arg;
int ok = PyArg_ParseTuple(args,"Oi",&pyRuleHandler, &arg);
if(!ok) return 0;
void * temp = PyCObject_AsVoidPtr(pyFooObject);
FooCPlusPlus* obj = static_cast<FooCPlusPlus*>(temp);
obj->method(arg); // some c++ method
return PyCObject_FromVoidPtr((void *) ruleHandler, NULL);
}
It fails at "bar"'s return statement...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,终于我知道问题出在哪里了:
我们应该从“bar”函数输入参数返回:
而不是
Well, finally I know where the problem was:
we should return from "bar" function input args:
instead of