用Python封装C;free(char*)无效指针



我正在学习本教程中关于用Python包装C/C++的内容。我已经逐字逐句地复制了示例代码,但仍将在下面列出。

你好。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;
}

脚本CCD_ 1定义了一个简单的";你好";函数,以及一个返回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脚本中,其成员函数应该是可访问的,并且已经被证明是可访问,但无效指针错误除外。我在这方面花了很多时间,但都无济于事。请帮忙。

根据文档,PyArg_ParseTuple()生成的指针不应该被释放:

此外,您不必自己释放任何内存,除非使用es、es#、et和et#格式。

消除free(result);调用应该可以停止崩溃。

最新更新