简体   繁体   English

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

[英]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. 我实际上是用cffi模块编写一个python程序来测试我的C / ASM库,并且设法使它起作用。 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. 但我不知道如何访问字符串中间的字符地址,以将其传递给我的lib函数。 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'hello world'

b'\\x00\\x00\\x00\\x00\\x00 world' b'\\ x00 \\ x00 \\ x00 \\ x00 \\ x00世界'

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 TypeError:ctype'void *'的初始化程序必须是cdata指针,而不是int

also tried with id(), with no success... 也尝试使用id(),但没有成功...

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不太熟悉,但是似乎不太喜欢它,所以这里的帮助很少,谢谢!

Python 3.7.0 的Python 3.7.0

ok found the solution use ffi.new() and ffi.tostring() 确定找到解决方案使用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))

output: 输出:

b'hello world' b'hello world'

b'hello' b'hello'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Python的CFFI将指针传递给C函数? - How do I pass a pointer to a C function with Python's CFFI? 如何使用cffi嵌入在C语言中返回字符串的Python函数? - How can I embed a Python function that returns a string in C using cffi? 我是否需要释放从CFFI调用的C函数返回的内存? - Do I need to free memory returned from a C function called via CFFI? 我们如何在 Java(JNA) 中获取由 Python function 使用 CFFI 返回的字符串 - How do we get String in Java(JNA), that returned by Python function using CFFI 如何将Numpy ND数组转换为CFFI C ++数组并再次返回? - How do I convert a numpy ND-array to a CFFI C++ array and back again? 如何使用 CFFI 将包含其标头的 C 库包装到 python 程序中? - How do I wrap a C-library including its header into a python program using CFFI? 如何使用 CFFI 将多维 Numpy 数组传递给 C 函数? - How to pass multidimensional Numpy arrays to C function using CFFI? 如何在Python中获取CFFI函数的`const`修饰符? - How can I get the `const` modifier of a CFFI function in Python? 如何将不是字母或数字的字符串中的字符发送到字符串的末尾? - How do I send a character from a string that is NOT a letter or a number to the end of the string? 如何用 function 做字符串替换字符? - How to do string replacement character with function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM