C:typedef 结构内的函数指针 [英] C: Function pointer inside a typedef struct

查看:39
本文介绍了C:typedef 结构内的函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 C 中创建一个链表,但试图在某种 C++ 风格的类中很好地打包它.但是我在 C 中使用函数指针时遇到了一些问题.

I am trying to create a linked list in C but trying to pack it nicely in somewhat of a C++ style class. I am having some issues however using function pointers in C.

typedef struct linkedList {
    int count;
    struct msgNode *front;
    struct msgNode *back;
    void (*addMSG)(unsigned char *, int, struct linkedList *);
} msgList;

void addMSG(unsigned char *data, int size, struct linkedList *self);

理想情况下,我希望您可以使用它来创建列表,然后添加您可以简单地在结构中调用方法"(函数),模拟您在 C++ 中看到的行为.

Ideally, I would like to have it such that you can make you list and then to add you can simply call a "method"(function) within the structure, simulating behavior you would see in C++.

目前我在调用 addMSG 时遇到分段错误,这当然是因为 addMSG 没有指向函数.但是,我不想在每次要使用链表时都指定一个函数来指向它.有没有什么好的方法可以让函数指针不隐式指向函数,或者你必须隐式指向函数?

Currently I get a segmentation fault when I call addMSG, which of-course is because addMSG is not pointing to a function. However, I don't want to have to specify a function to point to every single time I want use a linked list. Is there any nice way to have function pointers without implicitly having to point to the function, or do you have to implicitly point it to the function?

这只是此处显示的部分实现.最后,这个结构将具有所有必要的功能.这只是为了让这个问题简短而切中要害.

This is only the partial implementation shown here. At the end, this struct will have all the necessary functions. This is just for the sake of keeping this question short and to the point.

推荐答案

您需要将功能分配给成员.我还建议给他们不同的名字:

You need to assign the function to the member. i also recommend giving them different names:

typedef void (*addMSGFunc)(unsigned char *, int, struct linkedList *);

typedef struct linkedList {
    int count;
    struct msgNode *front;
    struct msgNode *back;
    addMSGFunc addMSG;
} msgList;

void addMSGImpl(unsigned char *data, int size, struct linkedList *self)
{
    ...
}

然后在创建 msgList 之后:

And then after creating a msgList:

msgList myList;
myList.addMSG = addMSGImpl;

这篇关于C:typedef 结构内的函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆