ctypes return a string from c function

后端 未结 5 2140
死守一世寂寞
死守一世寂寞 2020-12-14 04:04

I\'m a Python veteran, but haven\'t dabbled much in C. After half a day of not finding anything on the internet that works for me, I thought I would ask here and get the hel

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 04:45

    Your problem is that greeting was allocated on the stack, but the stack is destroyed when the function returns. You could allocate the memory dynamically:

    #include 
    #include 
    #include 
    
    const char* hello(char* name) {
        char* greeting = malloc(100);
        snprintf("Hello, %s!\n", 100, name)
        printf("%s\n", greeting);
        return greeting;
    }
    

    But that's only part of the battle because now you have a memory leak. You could plug that with another ctypes call to free().

    ...or a much better approach is to read up on the official C binding to python (python 2.x at http://docs.python.org/2/c-api/ and python 3.x at http://docs.python.org/3/c-api/). Have your C function create a python string object and hand that back. It will be garbage collected by python automatically. Since you are writing the C side, you don't have to play the ctypes game.

    ...edit..

    I didn't compile and test, but I think this .py would work:

    import ctypes
    
    # define the interface
    hello = ctypes.cdll.LoadLibrary('./hello.so')
    # find lib on linux or windows
    libc = ctypes.CDLL(ctypes.util.find_library('c'))
    # declare the functions we use
    hello.hello.argtypes = (ctypes.c_char_p,)
    hello.hello.restype = ctypes.c_char_p
    libc.free.argtypes = (ctypes.c_void_p,)
    
    # wrap hello to make sure the free is done
    def hello(name):
        _result = hello.hello(name)
        result = _result.value
        libc.free(_result)
        return result
    
    # do the deed
    print hello("Frank")
    

提交回复
热议问题