2
votes

I am trying to load and call functions from DLL file in python. A part of my code is below:

listdyn= (ctypes.c_char_p * len(list1_))(*list1_)

print type(listdyn)

Output: main.c_char_p_Array_64'

I should do a bitwise operation with c_char_p(or string)

I have 2 questions

1) Does listdyn became pointer of pointers by this way?

2) How do I convert into string or c_char_p

1

1 Answers

0
votes

2) How do I convert into string or c_char_p If you have only string values in list1_ then use the next code to convert listdyn to string:

print ''.join([ctypes.cast(i, ctypes.c_char_p).value for i in listdyn])

or simply (as eryksun correctly noticed):

print ''.join(listdyn[:])

but the problem is, that it is possible to have int values in list1_. E. g.:

list1_ = ['Demo', '', 'string', 0, 'value', 123]

String objects' values ('Demo', '', 'string' and value) could be found by their (objects') addressess, but int values (0 and 123) will be stored in c_char_p_Array as addresses (0x00 and 0x7b = 123 in hex). Therefore if you'll try to get the value of 5th item (123) using code:

print ctypes.cast(listdyn[5], ctypes.c_char_p).value, on Windows the next error will occur:

ValueError: invalid string pointer 0x000000000000007B

But under Linux segmentation fault occur.

So, if int values are in list1_ under Windows try to use this code:

result_list = []
listdyn_addr = (ctypes.c_void_p * len(listdyn)).from_buffer(listdyn)
for i in xrange(0, len(listdyn)):
    str_pointer = listdyn_addr[i]
    try:
        value = ctypes.c_char_p(str_pointer).value
        if value == '':
            result_list.append('')
        else:
            result_list.append(0 if not value else value)
    except:
        result_list.append(str_pointer)
print result_list

Result:

['Demo', '', 'string', 0, 'value', 123]