Stephane
Stephane

Reputation: 153

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

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

Upvotes: 3

Views: 1510

Answers (1)

Stephane
Stephane

Reputation: 153

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'

Upvotes: 2

Related Questions