通过Python向我的C代码发送以null结尾的字符串

2024-06-12 13:31:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在向我的BPF C代码发送字符串,我不确定传入的字符串是否以null结尾。如果不是,有没有办法使它们以null结尾?我将我的代码行发送到BPF,这样我就可以使用我的stringCounter函数手动计算它们,但我一直在遗憾地遇到一个永久循环。下面是我的Python代码的样子:

b = BPF(src_file="hello.c")

lookupTable = b["lookupTable"]
#add hello.csv to the lookupTable array
f = open("hello copy.csv","r")
contents = f.readlines()
for i in range(0,len(contents)):
    string = contents[i].encode('utf-8')
    lookupTable[ctypes.c_int(i)] = ctypes.create_string_buffer(string, len(string))

这是我为以null结尾的字符串计数器找到的代码

int stringLength(char* txt)
{
    int i=0,count=0;
    
    while(txt[i++]!='\0'){
        count+=1;
    }
    
    return count;
}

Tags: csv字符串代码txthellostringlencount
2条回答

我不熟悉BPF,但对于ctypes,如果字符串没有被C代码修改,则不需要create_string_buffer,因为它用于创建可变缓冲区,Python Unicode和字节字符串总是分别以nul结尾wchar_t*char*传递给C代码。假设您的函数位于test.dlltest.so中:

import ctypes as ct

dll = ct.CDLL('./test')
dll.stringLength.argtypes = ct.c_char_p,
dll.stringLength.restype = ct.c_int

print(dll.stringLength('somestring'.encode()))  # If string is Unicode
print(dll.stringLength(b'someotherstring'))     # If already a byte string

输出:

10
15

注意,这并不排除字符串本身包含nul,但在这种情况下,count函数将返回一个较短的值:

print(dll.stringLength(b'some\0string'))  # Output: 4

假设不要求BPF对象具有硬编码的ctypes类型作为索引和值,那么您的代码可能按照以下方式编写

with open("hello copy.csv") as file:
    for i,line in enumerate(file):
        lookupTable[i] = string.encode()

ctypes.create_string_buffer(string, len(string))不是以零结尾的。但是ctypes.create_string_buffer(string)是。很容易看出,因为ctypes.create_string_buffer(string)[-1]b'\x00',而ctypes.create_string_buffer(string, len(string))string中的最后一个字节

换句话说,如果您想要一个以零结尾的缓冲区,让create_string_buffer算出长度。(它使用Python字节对象的实际长度,因此如果您担心的话,它不会被内部NUL字节愚弄。)

相关问题 更多 >