left4bread
left4bread

Reputation: 1634

How to test for pointer equality in Python ctypes?

If I have the following C library

#include <stdint.h>

int64_t* foo(int64_t *x) {
    return x;
}

and I invoke the function from Python ctypes like so:

ptr = (ctypes.c_int64 * 100)()
rval = api.foo(ptr)

Naively I'd assume I can just assertEqual(rval, ptr), but that fails. Printing rval and ptr respectively I get

<reference_project.LP_c_longlong object at 0x0000021A563BBDC0>
<tests.c_longlong_Array_100 object at 0x0000021A563BBF40>

How can I compare ptr and rval for equality from Python?

Upvotes: 1

Views: 513

Answers (1)

left4bread
left4bread

Reputation: 1634

Answering my own question, casting the pointers to c_void_p and taking .value seems to do the job:

ptr_via_void = ctypes.cast(ptr, ctypes.c_void_p).value
rval_via_void = ctypes.cast(rval, ctypes.c_void_p).value

print(ptr_via_void)  # 2373661818336
print(rval_via_void) # 2373661818336

assertEqual(ptr_via_void, rval_via_void)

However, just omitting .value does not work:

ptr_via_void = ctypes.cast(ptr, ctypes.c_void_p)
rval_via_void = ctypes.cast(rval, ctypes.c_void_p)

print(ptr_via_void)  # c_void_p(1988667444176)
print(rval_via_void) # c_void_p(1988667444176)

# Although both print the same value, this FAILS:
assertEqual(ptr_via_void, rval_via_void)

I can't believe there is seemingly no better way.

Upvotes: 1

Related Questions