Search code examples
pythoncpointersctypesextern

passing pointer from python var to c lib


I have a fixed C libary as DLL file. The DLL file has some security functions which is why i cant look into the libary. I only know the functionname and the type of data is needed.

I need to give the function a Pointer to my var in Python, the adress in the memory. I try using ctypes but it wont work. For the loading of the lib. i use ctypes.

This is the function with all needed variables i need to start.

function  (
 const unsigned char* input_array,
 unsigned int multiply_by,
 unsigned char* output_array
);  

So i initialize my vars in Python like this:

input_array = "100"
multiply_by = 5
output_array = "000"

After that i load my lib and start the function.

lib = CDLL('func_lib.dll')
lib.function( hex(id(input_array)),
                 multiply_by,
                 hex(id(output_array))
             )

The function wont change the variable output_array, which is the goal of it. I can see that the function is called because no error is called. Do i handle the pointers wrong?

EDIT: I simplified the function to 3 vars, it would be the same for more. Also i think the input_array is the problem. The called function gets me a feedback-code which says, that the input_array is wrong. I dont know how to send the pointer adress to the function.


Solution

  • The parameter bigarray is declared const unsigned char * in the function signature. If this is correct, then there are few chances for the bigarray variable to change.

    EDIT To summarize comments, here is a hopefully working sample, given the original function signature.

        # Load the lib
        lib = CDLL('func_lib.dll')
    
        # Defines signature, based on C one
        lib.function.argtypes = [ c_char_p, c_uint, c_char_p ]
    
        # Call parameters
        data_in = b'Sample input'
        data_out = create_string_buffer(16)
    
        # Call
        lib.function(data_in, 16, data_out)
    

    One guess here, i supposed that the second parameter is a buffer size, hence in the sample call i gave the same value as to create_string_buffer.
    The call to create_string_buffer is required here, has it is an output for your function. Beware that there is an obvious buffer overrun risk here.