Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cffi: How do i send the address of a character of a string to a C function?

Tags:

python

cffi

i am actually writing a python program with cffi module to test my C/ASM library, and i managed to make it work. But i don't know how to access the address of a character in the middle of a string to pass it to my lib function. For exemple:

def my_bzero_test():
   str = b"hello world"
   print(str)
   lib.ft_bzero(str, 5)
   print(str)

that prints:

b'hello world'

b'\x00\x00\x00\x00\x00 world'

But how can i test something like:

def my_bzero_test():
   str = b"hello world"
   print(str)
   lib.ft_bzero(str + 5, 5) # C-style accessing &str[5]
   print(str)

i tried different stuff, like:

def my_bzero_test():
    str = ctypes.create_string_buffer(b"hello world")
    addr = ctypes.addressof(str)
    print(hex(addr))
    print(str)
    lib.ft_bzero(addr + 5, 5)
    print(str)

output:

TypeError: initializer for ctype 'void *' must be a cdata pointer, not int

also tried with id(), with no success...

I am not very familiar with python but it seems liek it is not a trivial utilisation of it, so little help here would be appreciated, thanks !

Python 3.7.0

like image 876
Stephane Avatar asked Nov 30 '25 10:11

Stephane


1 Answers

ok found the solution use ffi.new() and ffi.tostring()

str = ffi.new("char[]", b"hello world")
print(ffi.string(str))
lib.ft_bzero(str + 5, 5)
print(ffi.string(str))

output:

b'hello world'

b'hello'

like image 121
Stephane Avatar answered Dec 02 '25 00:12

Stephane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!