简体   繁体   中英

Creating a pointer to a 2D char array in Python

I have some C code which I have wrapped in python. As part of this code it generates a pointer to a 2D char array (string pairs in a larger table).

I wanted a way to generate a compatible table in python and pass the pointer to C. The point needs to be of type LP_LP_char_p and needs to be able to be referenced as ptr[2][1] or similar.

I created some code that works and so I am posting it here:

from ctypes import POINTER, pointer, c_char, c_char_p, addressof, cast

rows = 13
cols = 2
line_len = 12
type_char_p = POINTER(c_char_p)
type_char_pp = POINTER(POINTER(c_char_p))

char_p_array = ((c_char_p * cols) * rows)()
char_pp_array = (type_char_p * rows)()

for i in range(rows):
    for j in range(cols):
        char_p_array[i][j] = f'msg {i} {j}'.encode('raw_unicode_escape')
    char_pp_array[i] = char_p_array[i]
    
p = cast(char_pp_array, type_char_pp)

In:     p
Out:    <__main__.LP_LP_c_char_p at 0x28acdb477c8>

In:     p.contents.contents.value
Out:    b'msg 0 0'

In:     p[0][0]
Out:    b'msg 0 0'

In:     p[1][1]
Out:    b'msg 1 1'

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