首页 > 解决方案 > 避免在 cython 中对链表进行嵌套结构重定义

问题描述

我想将与链表结构相关的代码移动到单独的文件中。此链表用于 .pyx 和 .c 文件。

当前实现:cython_file.pyx:

ctypedef struct linked_list

ctypedef struct linked_list:
    double price
    double volume
    int data
    linked_list *next_cell
...

c_file.c:

typedef struct linked_list {
    double price;
    double volume;
    int data;
    struct linked_list * next_cell;
} linked_list;
...

我想要的是创建LinkedList.h,LinkedList.cLinkedList.pxd, 它将包含以下内容:

链表.h:

typedef struct linked_list {
    double price;
    double volume;
    int data;
    struct linked_list * next_cell;
} linked_list;
...

链表.c:

#include "LinkedList.h"
...

链表.pxd:

cdef extern from "LinkedList.h":
    ctypedef struct linked_list

    ctypedef struct linked_list:
        double price
        double volume
        int data
        linked_list * next_cell

我想以下列方式使用它:在 cython_file.pyx 中:

from LinkedList cimport *
...

在 c_file.c 中:

#include "LinkedList.h"
...

当我尝试编译第二个变体时,出现错误: LinkedList.h(1): error C2011: 'linked_list': 'struct' type redefinition

我想这个问题是由于嵌套结构而发生的

标签: pythonclinked-listcython

解决方案


为避免redefinition errors您必须在头文件中使用包含保护。

//LinkedList.h
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
...
#endif

包含保护是预处理器宏,可防止多次包含头文件。

它基本上检查是否LINKEDLIST_H已定义。如果是这样,它会跳过if子句中的所有内容。否则它定义它。

这样您就可以避免多次从标题中重新定义结构,这可能是导致此错误的原因。


推荐阅读