3

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 Answers 2

5

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your solution, I chose it as the answer because it is more anonymous method like, and only took two lines of code :) Thanks again for taking the time to answer, much appreciate!
3

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)

2 Comments

I wish I could select both response as solutions because they both worked as expected. Thank you for your solution.
But this did allow me to initialize a large array which much less code, thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.