如何在内核 C 中将 size_t 转换为 char*?

How to convert size_t to char* in kernel C?

我在我的内核模块中使用了一个 size_t 变量。当我想将它写入文件时,必须根据 vfs_write 签名将其转换为 char*

extern ssize_t vfs_write(struct file *, const char __user *, size_t, loff_t *);

我使用这个函数,它使用 vfs_write(我在网上找到的):

int file_write(struct file *file, unsigned long long offset, unsigned 
char *data, unsigned int size) 
{
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();
    set_fs(get_ds());

    ret = vfs_write(file, data, size, &offset);

    set_fs(oldfs);
    return ret;
}

nbytes 变量是 size_t 我尝试 (char *) 强制转换 nbyteschar* 但内核立即崩溃。这是我的代码。

index_filename = "/home/rocket/Desktop/index_pool";
index_file = file_open(index_filename,O_WRONLY | O_CREAT, 0644);
if(index_file == NULL)
    printk(KERN_ALERT "index_file open error !!.\n");
else{
    // file_write(index_file, 0, nbytes, nbytes); => this crashs also
    file_write(index_file, 0, (char*) nbytes, 100);
    file_close(index_file);
}

有没有办法在内核中安全地将 size_t 类型转换为 char * 类型?

当然它会崩溃 - 你试图写入 100 字节的任何内存位置 nbytes 指向。因为它不是指针,所以它极不可能成为有效的内存区域。即使是,它的大小也可能不到 100 个字节。

您想传递给 vfs_write 的是指向 nbytes 的指针。其大小为 sizeof(nbytes)。所以你会像这样调用你的包装函数

file_write(index_file, 0, (char*) &nbytes, sizeof(nbytes));

这将写出 size_tnbytes

的内存位置有多少字节

如果你想写出 nbytes 的值,这与你在问题中提出的不同,你需要将它存储在一个字符串中,然后像这样将它传递给你的函数:

char temp_string[20];
sprintf(temp_string,"%zu",nbytes);
file_write(index_file, 0, temp_string, strlen(temp_string));

Is there a way to safely convert size_t type to char * one in Kernel ?

是的,有。 你应该使用 linux/kernel.h 库中的 sprintf 函数

所以你应该这样做:

sprintf(destination_char_star, "%zu", your_s_size_var);

请注意,如果需要,您应该为 char star 分配内存。