pythoncpointersfficffi

Comparing C pointers in Python


I am looking for an easier way to compare the data at two C-pointers in python. The method I have working now:

import cffi

ffi = cffi.FFI()

def ref_char_p(char_p):
    arr = []
    null_term = 0;
    while(char_p[null_term] != 0):
        null_term += 1

    for x in range(0, null_term):
        arr.append(char_p[x])
    return arr

char_p = ffi.new("char[]", '\x41\x42\x43')
char_p2 = ffi.new("char[]", '\x41\x42\x43')

if(ref_char_p(char_p) == ref_char_p(char_p2)):
    print "equal"
else:
    print "not equal"

Is there any way I can do something closer to:

if(char_p == char_p2):
    print "equal"

I have read through the cffi docs but have not found anything promising.


Solution

  • You can use ffi.string() to convert the char array to a bytes object:

    ffi.string(char_p) == ffi.string(char_p2)