c - 在设备驱动程序中使用 kmalloc

标签 c struct kernel device-driver kmalloc

在一项作业中,我必须为一副纸牌创建一个设备驱动程序。但是,我在结构数组上使用 kmalloc 时遇到问题。结构数组,大小为 52。到目前为止,我有以下内容(显然它是不完整的):

#include <linux/slab.h>         // kmalloc()
#include <linux/fs.h>           // everything
#include <linux/errno.h>        // error codes
#include <linux/types.h>        // ssize_t
#include <linux/fcntl.h>        // O_ACCMODE
#include <linux/miscdevice.h>
#include <asm/uaccess.h>        // copy_to_user copy_from_user

MODULE_LICENSE("GPL"); 

struct card{
   char num;
   char suit;
}; 

struct card deck[52];

static int __init_deck(void){
    int i;
    int returnValue;
    for(i = 0; i < 52; i++){
        deck[i] = kmalloc(sizeof(struct card), GFP_KERNEL); // error here
        if(!deck[i]){ // error here
            printk(KERN_ERR "Unable to allocate memory.");
        }
    }

    return returnValue;
}

当我尝试使用 error: incompatible types when assigning to type 'struct card' from type 'void *' for first and error 时出现错误: 第二个一元感叹号 的类型参数错误。我认为一旦 kmalloc 一个被修复,第二个就会消失,但我不知道出了什么问题以及如何解决它。

最佳答案

注意你的错误。您正在尝试将指针类型分配给 struct card。您似乎想要一组 card*

struct card *deck[52];

否则你根本不需要动态分配;你已经有 52 个有效的 card 对象。

关于c - 在设备驱动程序中使用 kmalloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23002806/

相关文章:

C 多线程应用程序结构

c size_t 变量未设置为零?

c - C 中的 Typedef 和结构

linux - insmod lkm.ko 在可加载内核模块中调用 cleanup_module 而不是 init_module

c - 如何在linux内核模式下获取字符串和字符串长度?

c - C中的文件I/O,无法删除以前写入的数据

python - 从 python 调用 C 或 C++ 是如何工作的?

for-loop - 如何在 Golang 中迭代结构中的 slice 或者是否可以在结构中使用 for 循环?

macos - setPowerState 是否总是在启动后调用?

c - C中getopt的错误处理