简体   繁体   中英

define *struct in ctypes

I need to convert regexitem *regex to ctype variable, any ideas?

C function expects func(regexitem *regex)

    char *regex1Groups[] = { "a","b","x","s" ,NULL};
    char *regex2Groups[] = { "l" ,NULL};

    regexitem regex[] = {
            {"bla", regex1Groups,4 },
            {"bla2",regex2Groups,1 }
    };

First i defined

class regexitem(Structure): 
        _fields = ("regex",c_char_p), ("groups",c_char_p*size), ("groupsize",c_int)

and ran into first problem, declaring array of regexitem because size of groups is not known in advance.

Structs can only contain variable-length arrays at their ends, and on top of that when you assign an array variable to something you aren't copying it, you're assigning the memory location of the first element of the array. So I'm betting that your regexitem struct contains a pointer to the array of char pointers rather than containing the array of char pointers itself. If that's the case, this might work:

class regexItem(Structure):
    _fields_ = [("regex", c_char_p),
                ("groups", POINTER(c_char_p)),
                ("groupsize", c_int),
                ]

(You can keep the assignment to _fields_ as a tuple of tuples rather than a list of tuples if you want to.)

Oh, for your regex groups, it'd be something like this:

regex1Groups = (c_char_p * 5)("a", "b", "x", "s", None)
regex2Groups = (c_char_p * 2)("l", None)

And then your array of regexitem s would be like so:

regex = (regexItem * 2)(("bla", regex1Groups, 4),
                        ("bla2", regex2Groups, 1))

Look through the ctypes documentation if you want to know more.

http://docs.python.org/library/ctypes.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM