2
votes

I'm writing a Python C Extension that needs to return a CTypes pointer to a char array in memory (I need to interface with another Python library that expects a CTypes pointer).

I cannot find any documentation on any kind of CTypes interface for C. Are there any workarounds, like calling the Python pointer constructor?

static PyObject *get_pointer(myObject *self)
{
    char *my_pointer = self->internal_pointer;
    return PyCTypes_Pointer(my_pointer); /* how do I turn 'my_pointer' into 
              a Python object representing a CTypes pointer? */
}

Thanks in advance.

1
Am I missing something? Aren't you asking for: docs.python.org/library/ctypes.html#ctypes-pointers - mjhm
That is Python code. I need to construct the pointer from C. - Vicent Marti
WOuld you like to use SWIG? It is so powerful~~~ - kaitian521

1 Answers

1
votes

Even though you're programming in C, try using Python itself. Sadly I don't know of any kind of CTypes interface for C and couldn't find any hint in the sources. Maybe you'll be able to write your own PyCTypes_Pointer method with the following.

I didn't do any cleanup, error checking or handling here, but it's working with Python 2.7 and 3.4 for me.

#include <Python.h>

static const char *test = "Testing Python ctypes char pointer ..."; 

static PyObject *c_char_p = NULL;
static PyObject *c_void_p = NULL;
static PyObject *cast = NULL;

static PyObject * char_p ( void ) {
    PyObject *p = PyLong_FromVoidPtr((void *) test);
    p = PyObject_CallFunction(c_void_p, "O", p);
    return PyObject_CallFunction(cast, "OO", p, c_char_p);
}

static PyObject *len ( void ) {
    return PyLong_FromSize_t(strlen(test));
}

static PyMethodDef methods[] = {
    {"char_p", (PyCFunction) char_p, METH_NOARGS, ""},
    {"len", (PyCFunction) len, METH_NOARGS, ""},
    { NULL }
};

#if PY_MAJOR_VERSION >= 3
static PyModuleDef module = {PyModuleDef_HEAD_INIT, "pyt", "", -1, methods,
    NULL, NULL, NULL, NULL};
#define INIT_FUNC PyInit_pyp
#else
#define INIT_FUNC initpyp
#endif

PyMODINIT_FUNC INIT_FUNC ( void ) {
    PyObject* m;

    PyObject *ctypes = PyImport_ImportModule("ctypes");
    PyObject *c_char = PyObject_GetAttrString(ctypes, "c_char");
    c_char_p = PyObject_CallMethod(ctypes, "POINTER", "O", c_char);
    c_void_p = PyObject_GetAttrString(ctypes, "c_void_p");
    cast = PyObject_GetAttrString(ctypes, "cast");

#if PY_MAJOR_VERSION >= 3
    m = PyModule_Create(&module);
#else
    m = Py_InitModule("pyp", methods);
#endif

    return (PyMODINIT_FUNC) m;
}

Just build with

from __future__ import print_function
from distutils.core import Extension, setup
import sys
sys.argv.extend(["build_ext", "-i"])
setup(ext_modules = [Extension('pyp', ['pyp.c'])])
import pyp
c = pyp.char_p()
print(c[:pyp.len()])

and get an output like

<class 'ctypes.LP_c_char'> Testing Python ctypes char pointer ...

If you're handling zero-terminated strings only, you might be able to use ctypes.c_char_p directly, maybe ...