为什么需要 container_of 而 kmalloc 已经 returns 指向内存位置的指针?
Why need container_of when kmalloc already returns the pointer to memory location?
kmalloc() returns 指向初始化期间分配的内存位置的指针,如果使包含 cdev 的结构指向它,为什么需要在打开文件操作中执行 container_of再次调用以获取包含 cdev 的结构的地址?
我猜你指的是这样的东西:
http://www.cs.uni.edu/~diesburg/courses/dd/code/scull/pipe.c
static int scull_p_open(struct inode *inode, struct file *filp)
{
struct scull_pipe *dev;
dev = container_of(inode->i_cdev, struct scull_pipe, cdev);
// ...
而kmalloc
是这样使用的:
scull_p_devices = kmalloc(scull_p_nr_devs * sizeof(struct scull_pipe), GFP_KERNEL);
其中 struct scull_pipe
是:
struct scull_pipe {
wait_queue_head_t inq, outq; /* read and write queues */
char *buffer, *end; /* begin of buf, end of buf */
int buffersize; /* used in pointer arithmetic */
char *rp, *wp; /* where to read, where to write */
int nreaders, nwriters; /* number of openings for r/w */
struct fasync_struct *async_queue; /* asynchronous readers */
struct semaphore sem; /* mutual exclusion semaphore */
struct cdev cdev; /* Char device structure */
};
使用 container_of
的原因是在 scull_p_open
回调中你没有指向 struct scull_pipe
实例的指针,但你可以访问 cdev
成员struct scull_pipe
结构(通过 inode->i_cdev
)。为了得到cdev
的容器地址(换句话说struct scull_pipe
实例的地址),你需要使用container_of
:
struct scull_pipe *dev;
dev = container_of(inode->i_cdev, struct scull_pipe, cdev);
kmalloc() returns 指向初始化期间分配的内存位置的指针,如果使包含 cdev 的结构指向它,为什么需要在打开文件操作中执行 container_of再次调用以获取包含 cdev 的结构的地址?
我猜你指的是这样的东西:
http://www.cs.uni.edu/~diesburg/courses/dd/code/scull/pipe.c
static int scull_p_open(struct inode *inode, struct file *filp)
{
struct scull_pipe *dev;
dev = container_of(inode->i_cdev, struct scull_pipe, cdev);
// ...
而kmalloc
是这样使用的:
scull_p_devices = kmalloc(scull_p_nr_devs * sizeof(struct scull_pipe), GFP_KERNEL);
其中 struct scull_pipe
是:
struct scull_pipe {
wait_queue_head_t inq, outq; /* read and write queues */
char *buffer, *end; /* begin of buf, end of buf */
int buffersize; /* used in pointer arithmetic */
char *rp, *wp; /* where to read, where to write */
int nreaders, nwriters; /* number of openings for r/w */
struct fasync_struct *async_queue; /* asynchronous readers */
struct semaphore sem; /* mutual exclusion semaphore */
struct cdev cdev; /* Char device structure */
};
使用 container_of
的原因是在 scull_p_open
回调中你没有指向 struct scull_pipe
实例的指针,但你可以访问 cdev
成员struct scull_pipe
结构(通过 inode->i_cdev
)。为了得到cdev
的容器地址(换句话说struct scull_pipe
实例的地址),你需要使用container_of
:
struct scull_pipe *dev;
dev = container_of(inode->i_cdev, struct scull_pipe, cdev);