Search code examples
pythonshared-librariesdllimport

dynamically calling an ffi function in python?


I'm writing a simple program that needs to reach out to libc for some functions. My problem is that I don't know what these functions are when writing the program ie. the functions that will be called are imported dynamically, based on some user input.

How can I do this? Ideally I'd like to have a python dictionary of all the functions from the imported library.

Thanks!


Solution

  • You could use the ctypes library, it allow you to call functions in shared libraries written in C.

    Here is an example:

    import ctypes
    
    def load_library(lib_name):
        try:
            return ctypes.CDLL(lib_name)
        except OSError:
            print(f"Failed to load library: {lib_name}")
            return None
    
    def load_functions(library, function_names):
        functions = {}
        for name in function_names:
            try:
                functions[name] = getattr(library, name)
            except AttributeError:
                print(f"Failed to load function: {name}")
        return functions
    
    libc = load_library("libc.so.6")
    if libc is not None:
        function_names = ["strlen", "strcpy", "strcmp"]
        libc_functions = load_functions(libc, function_names)
    
        strlen = libc_functions["strlen"]
        strlen.argtypes = [ctypes.c_char_p]
        strlen.restype = ctypes.c_size_t
    
        s = b"hello world"
        print(strlen(s))