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

查看:122
本文介绍了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天全站免登陆