gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:13:50 26 4
gpt4 key购买 nike

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

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

打印:

b'hello world'

b'\x00\x00\x00\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: initializer for ctype 'void *' must be a cdata pointer, not int

也尝试了 id(),但没有成功......

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

python 3.7.0

最佳答案

确定使用 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'hello world'

b'hello'

关于python - cffi:如何将字符串字符的地址发送到 C 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53140955/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com