简体   繁体   中英

Python | ctypes structure return pointer

I'm hoping for some help with ctypes structures and pointers.

Here is my C code signatures

typedef struct ApiReturn
{
   int error;
   char* errorMessage;
} ApiReturn;

// if this call fails, we'll declare instantiate the errorMessage pointer and
// set the appropriate value for error.
ApiReturn DoSomething();

// this frees the memory in clear.
void Api_Clear(char* clear);

And here's the ctypes code:

class ApiReturn(Structure):
    _fields_ = [('error', c_int),
                ('errorMessage', c_char_p)]

def check_api_return(api_return):
    # 0 means api call succeeded.
    if api_return.error != 0:
        get_global_lib().Api_Clear(api_return.errorMessage)
        raise Exception('API call failed with' + api_return.errorMessage)

do_something = get_global_lib().DoSomething
do_something.restype = ApiReturn

This python code is wrong because api_return.errorMessage has instantiated a new python string, but I'm having trouble accessing the pointer errorMessage directly through the field member.

The rest of the library is working as expected. I'd appreciate any help on this issue.

I'll answer my own question after spending more time researching it. It turns out I needed to define the python structure differently in order to access the pointer.

class ApiReturn(Structure):
    _fields_ = [('error', c_int),
                ('errorMessage', POINTER(c_char))]

cp = pointer(api_return).contents.errorMessage
error_msg = cast(cp, c_char_p).value
get_global_lib().Api_Clear(cp)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM