Commit 10621a05 authored by Stefan Behnel's avatar Stefan Behnel

docs: Add an example on how to use verbatim C code to work around version specific struct fields.

See https://github.com/cython/cython/issues/4310
parent bc43abf7
typedef struct {
int field1;
int field2;
int newly_added_field;
} StructType;
static StructType global_struct;
static StructType *get_struct_ptr() {
return &global_struct;
}
#define C_LIB_VERSION 20
cdef extern from "struct_field_adaptation.h":
"""
#define HAS_NEWLY_ADDED_FIELD (C_LIB_VERSION >= 20)
#if HAS_NEWLY_ADDED_FIELD
#define _mylib_get_newly_added_field(a_struct_ptr) ((a_struct_ptr)->newly_added_field)
#define _mylib_set_newly_added_field(a_struct_ptr, value) ((a_struct_ptr)->newly_added_field) = (value)
#else
#define _mylib_get_newly_added_field(a_struct_ptr) (0)
#define _mylib_set_newly_added_field(a_struct_ptr, value) ((void) (value))
#endif
"""
# Normal declarations provided by the C header file:
ctypedef struct StructType:
int field1
int field2
StructType *get_struct_ptr()
# Special declarations conditionally provided above:
bint HAS_NEWLY_ADDED_FIELD
int get_newly_added_field "_mylib_get_newly_added_field" (StructType *struct_ptr)
void set_newly_added_field "_mylib_set_newly_added_field" (StructType *struct_ptr, int value)
cdef StructType *some_struct_ptr = get_struct_ptr()
print(some_struct_ptr.field1)
if HAS_NEWLY_ADDED_FIELD:
print(get_newly_added_field(some_struct_ptr))
......@@ -400,6 +400,11 @@ It is also possible to combine a header file and verbatim C code::
In this case, the C code ``#undef int`` is put right after
``#include "badheader.h"`` in the C code generated by Cython.
Verbatim C code can also be used for version specific adaptations, e.g. when
a struct field was added to a library but is not available in older versions:
.. literalinclude:: ../../examples/userguide/external_C_code/struct_field_adaptation.pyx
Note that the string is parsed like any other docstring in Python.
If you require character escapes to be passed into the C code file,
use a raw docstring, i.e. ``r""" ... """``.
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment