[Python] Automatically encode/decode ctypes argument and return

Discussão em 'Python' iniciado por Stack, Abril 9, 2025.

  1. Stack

    Stack Membro Participativo

    I have a shared library exposing a function:

    const char* foo(const char* s);


    To call it from Python using ctypes, I can do the following:

    import ctypes

    foo = ctypes.cdll.LoadLibrary('foo.so')
    foo.foo.argtypes = [ctypes.c_char_p]
    foo.foo.restype = ctypes.c_char_p

    print(foo.foo('Hello World!'.encode('utf8')).decode('utf8'))


    Is there a way to embed the encode/decode('utf8') inside the type itself? I want to do the following:

    foo.foo.argtypes = [c_utf8_p]
    foo.foo.restype = c_utf8_p

    print(foo.foo('Hello World!'))


    I was able to handle the argtypes with following:

    class c_utf8_p:
    @classmethod
    def from_param(cls, obj: str):
    return obj.encode('utf8')


    But cannot figure out the return type. restype docs say assigning it to anything that is not a ctypes type is deprecated, plus truncates value to int which destroys 64-bit pointers. I would like to avoid using errcheck since logically I am not checking any errors, plus it would require setting two attributes for every function.

    Continue reading...

Compartilhe esta Página