How to initialize a ctypes array in Python from command line

3.5k views Asked by At

So I have been tasked with writing a Python script which accesses a Win 32 DLL to perform some functionality. This script needs to accept parameters from the command line then output other parameters.

I am using ctypes since it is the easiest way I have found to pass parameters to the Win 32 DLL methods but I was lucky enough to have a fixed array of values from the command line which I solved by doing such:

seed = (ctypes.c_ubyte * 12)(
    ctypes.c_ubyte(int(sys.argv[3], 16)), ctypes.c_ubyte(int(sys.argv[4], 16)),
    ctypes.c_ubyte(int(sys.argv[5], 16)), ctypes.c_ubyte(int(sys.argv[6], 16)),
    ctypes.c_ubyte(int(sys.argv[7], 16)), ctypes.c_ubyte(int(sys.argv[8], 16)),
    ctypes.c_ubyte(int(sys.argv[9], 16)), ctypes.c_ubyte(int(sys.argv[10], 16)),
    ctypes.c_ubyte(int(sys.argv[11], 16)), ctypes.c_ubyte(int(sys.argv[12], 16)),
    ctypes.c_ubyte(int(sys.argv[13], 16)), ctypes.c_ubyte(int(sys.argv[14], 16))
)

But this is not dynamic in anyway and I tried to perform this array initialization with a for loop inside the array initialization but without success.

I am completely new to Python and find it rather difficult to do what I consider simple tasks in other languages (not bashing the language, just not finding it as intuitive as other languages for such tasks).

So, is there a way to simplify initializing this array where there could be a variable amount of entries per se?

I have searched and searched and nothing I have found has solved my problem.

All positive and negative comments are always appreciated and both will always serve as a learning experience :)

2

There are 2 answers

1
Mark Tolonen On BEST ANSWER

From your example it looks like you have 14 parameters and the last 12 are hexadecimal bytes.

import ctypes
import sys

# Convert parameters 3-14 from hexadecimal strings to integers using a list comprehension.
L = [int(i,16) for i in sys.argv[3:15]]

# Initialize a byte array with those 12 parameters.
# *L passes each element of L as a separate parameter.
seed = (ctypes.c_ubyte * 12)(*L)
2
Hao Li On

Try this:

seed_list = []                   
for i in sys.argv[3:]:
    seed_list.append(ctypes.c_ubyte(int(i, 16)))
seed = (ctypes.c_ubyte * len(seed_list))(*seed_list)