Question

I am following this tutorial on wrapping C/C++ with Python. I have copied the example code verbatim, but will still list it below.

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;
}

The script hello.c defines a simple "hello" function, as well as a wrapper which returns a Python object, and (hypothetically) frees the c char * pointer. This is where the code fails with the run-time error: Error in '/usr/bin/python': free(): invalid pointer: 0x00000000011fbd44. While I believe the error should be limited to this scope, let's go over the rest of the wrapper just in case...

hello.c is included in the definition of a module, which allows its methods to be called in Python. The module is defined as such:

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);
}

Finally, a Python script is implemented to build the module:

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])

Once setup.py is run, the module can be imported into any Python script, and its member functions should be accessible, and have proven to be, with the exception of the invalid pointer error. I have spent many hours on this to no avail. Please help.

Was it helpful?

Solution

According to the documentation, pointers produced by PyArg_ParseTuple() should not be freed:

Also, you won’t have to release any memory yourself, except with the es, es#, et and et# formats.

Eliminating the free(result); call should stop the crash.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top