cffi:如何将字符串的字符地址发送到C函数



我实际上正在编写一个带有cffi模块的python程序来测试我的C/ASM库,并且我设法使它工作起来。但我不知道如何访问字符串中间的字符地址,以便将其传递给我的lib函数。例如:

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

打印:

b'你好世界'

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

但是我如何测试类似的东西

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

我尝试了不同的东西,比如:

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)

输出:

TypeError:ctype"void*"的初始值设定项必须是cdata指针,而不是int

也尝试过id((,但没有成功。。。

我对python不是很熟悉,但它似乎不是一个微不足道的利用,所以这里的帮助将不胜感激,谢谢!

Python 3.7.0

ok找到了使用ffi.new((和ffi.tostring((的解决方案

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

输出:

b'你好世界'

b'hello'

最新更新