Python ctypes and char**

Question:

I have the following structures in C:

struct wordSynonym
{
    wchar_t* word;
    char** synonyms;
    int numSynonyms;
};

struct wordList
{
    wordSynonym* wordSynonyms;
    int numWords;
};

And, I have the following in Python:

class wordSynonym(Structure):
    _fields_ = [ ("word", c_wchar_p),
                  ("synonyms", POINTER(c_char_p)), # Is this correct?
                  ("numSynonyms", c_int) ];

class WordList(Structure):
    _fields_ = [ ("wordSynonyms", POINTER(wordSynonym)),
                 ("numWords", c_int)];

What is the correct way to reference char** in python? That is, in the Python code, is POINTER(c_char_p) correct?

Asked By: Doo Dah

||

Answers:

I use this in my code:

POINTER(POINTER(c_char))

But I think both are equivalent.

Edit:
Actually they are not
http://docs.python.org/2/library/ctypes.html#ctypes.c_char_p

ctypes.c_char_p
Represents the C char * datatype when it points to a zero-terminated
string. For a general character pointer that may also point to binary
data, POINTER(c_char)
must be used. The constructor accepts an integer
address, or a string.

So POINTER(POINTER(c_char)) is for binary data, and POINTER(c_char_p) is a pointer to a C null-terminated string.

Answered By: iabdalkader

I was wondering how should we declare our char* in ctypes Python and what is the correct syntax to call it when we have a function that allocates the buffer and assign its address to the pointer (BinaryData here) but the content of this buffer is Binary Data so we cannot use c_char_p type ? Thanks.

from ctypes import *

lib = CDLL("./libtests.so")

def get_function(lib, function_name, return_type, arg_types) -> object:
    function = lib.__getattr__(function_name)
    function.restype = return_type
    function.argtypes = arg_types
    return function

def main():
    BinaryData = POINTER(c_char)
    get_buff = get_function(lib, "get_binarydata", None, [POINTER(POINTER(c_char))])
    get_buff(byref(BinaryData))
    print(BinaryData.contents)
    return 0
Answered By: Yanis
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.