Skip to content

Commit c2ef977

Browse files
authored
Merge pull request #73 from edwood-grant/patch-1
Fixing incorrect enum information and add alternatives
2 parents d8d2635 + 13c39d1 commit c2ef977

File tree

1 file changed

+75
-1
lines changed

1 file changed

+75
-1
lines changed

source/developer-guides/bindings/writing-a-vapi-manually/04-00-recognizing-vala-semantics-in-c-code/04-02-enums-and-flags.rst

Lines changed: 75 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,4 +64,78 @@ There is also a common tendency to use combinable bit patterns. These are conver
6464
CREATE
6565
}
6666
67-
In Vala, enums and flags may have member functions. In particular, ``strerr``-like functions are best converted to member functions.
67+
Supersets
68+
---------
69+
70+
If one set of enums or flags is a superset of another, but they are logically separate, You can create a different set of enums that refer to the same enum
71+
or defines.
72+
73+
For example:
74+
75+
.. code-block:: c
76+
77+
#define FOO_A 1
78+
#define FOO_B 2
79+
#define FOO_C 3
80+
#define FOO_D 4
81+
/* takes FOO_A or B only */
82+
void do_something(int);
83+
/* takes any FOO_ value */
84+
void do_something_else(int);
85+
86+
Can become this:
87+
88+
.. code-block:: vala
89+
90+
[CCode (cname = "int", cprefix = "FOO_", has_type_id = false)]
91+
public enum Foo { A, B }
92+
[CCode (cname = "int", cprefix = "FOO_", has_type_id = false)]
93+
public enum FooExtended { C, D }
94+
95+
You can then cast one enum to another:
96+
97+
.. code-block:: vala
98+
99+
var foo_enum = (Foo) FooExtended.C;
100+
101+
Member functions and constants
102+
------------------------------
103+
104+
In Vala, enums and flags may have member functions and constants.
105+
In particular, ``strerr``-like functions are best converted to member functions.
106+
107+
Enum aliases and ``to_string()``
108+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
109+
110+
The default function ``to_string()`` can cause problems if the enum has aliases (the C error ``duplicate case`` will trigger). So to solve this,
111+
you can create additional constants after the enum has been declared to add the missing enum aliases.
112+
113+
For example this enum:
114+
115+
.. code-block:: c
116+
117+
typedef enum {
118+
BAR_A,
119+
BAR_B,
120+
BAR_C,
121+
BAR_D,
122+
BAR_FIRST = BAR_A,
123+
BAR_LAST = BAR_D,
124+
} bar_e;
125+
126+
Will become:
127+
128+
.. code-block:: vala
129+
130+
[CCode (cname = "bar_e", cprefix = "BAR_", has_type_id = false)]
131+
public enum Bar {
132+
A,
133+
B,
134+
C;
135+
136+
[CCode (cname = "BAR_")]
137+
public const Bar FIRST;
138+
139+
[CCode (cname = "BAR_")]
140+
public const Bar LAST;
141+
}

0 commit comments

Comments
 (0)