用Python封装C;free(char *)无效指针
我正在跟着这个教程,学习如何用Python包装C/C++代码。我把示例代码逐字复制了,下面也会列出来。
hello.c
#include <stdio.h>
#include <Python.h>
// Original C Function
char * hello(char * what)
{
printf("Hello %s!\n", what);
return what;
}
// 1) Wrapper Function that returns Python stuff
static PyObject * hello_wrapper(PyObject * self, PyObject * args)
{
char * input;
char * result;
PyObject * ret;
// parse arguments
if (!PyArg_ParseTuple(args, "s", &input)) {
return NULL;
}
// run the actual function
result = hello(input);
// build the resulting string into a Python object.
ret = PyString_FromString(result);
free(result);
return ret;
}
这个脚本hello.c
定义了一个简单的“hello”函数,还有一个包装器,用来返回一个Python对象,并且(假设)释放了c char *指针。这里是代码出错的地方: Error in '/usr/bin/python': free(): invalid pointer: 0x00000000011fbd44
。虽然我认为这个错误应该只在这个范围内出现,但我们还是把包装器的其余部分看一遍,以防万一...
hello.c
被包含在一个模块的定义中,这样它的方法就可以在Python中调用。这个模块的定义如下:
hellomodule.c
#include "hello.c"
#include <Python.h>
// 2) Python module
static PyMethodDef HelloMethods[] =
{
{ "hello", hello_wrapper, METH_VARARGS, "Say hello" },
{ NULL, NULL, 0, NULL }
};
// 3) Module init function
DL_EXPORT(void) inithello(void)
{
Py_InitModule("hello", HelloMethods);
}
最后,实施一个Python脚本来构建这个模块:
setup.py
#!/usr/bin/python
from distutils.core import setup, Extension
# the c++ extension module
extension_mod = Extension("hello", ["hellomodule.c"]) #, "hello.c"])
setup(name = "hello", ext_modules=[extension_mod])
一旦运行了setup.py
,这个模块就可以被导入到任何Python脚本中,它的成员函数应该是可以访问的,除了无效指针的错误外,其他都证明是可以的。我为此花了很多时间,但没有找到解决办法。请帮帮我。
1 个回答
1
根据文档,使用PyArg_ParseTuple()
生成的指针是不用手动释放的:
此外,除了使用es、es#、et和et#格式时,你不需要自己释放任何内存。
去掉free(result);
这一行代码应该就能解决崩溃的问题。