最终目标:仅依赖 libclang 定义 @cunion
宏,在 julia 中模拟 C 语言 Union 的行为。
ref: integrate CUnion.jl
· Issue #1 · Gnimuc/CSyntax.jl
看上去有用的函数
- clang_Type_getSizeOf (CXType T) == sizeof 运算符 - cppreference.com
- clang_Type_getOffsetOf (CXType T, const char *S) == offsetof - cppreference.com
- clang_Type_getAlignOf (CXType T) == offsetof - cppreference.com
进度
- 20191218:能拿到 union 的大小
getUnionSize.jl
using Clang
const cl = Clang
trans_unit = parse_header("./utest.h")
root_cursor = getcursor(trans_unit)
childrens = children(root_cursor)
for ch in childrens
type_ch = cl.clang_getCursorType(ch)
union_size = cl.clang_Type_getSizeOf(type_ch)
print(ch.cursor)
println(" [$union_size]")
end
C union 测试样例
- 20191218
utest.h
// simple test
union int_char { // 4
int a;
char b;
};
union char_char { // 1
char a;
char b;
};
/*
padding test
*/
union char10 {
char arr[10];
};
union char13 {
char arr[13];
};
union int_char13 {
char name[13];
int age;
};
// [Union declaration - cppreference.com](https://en.cppreference.com/w/c/language/union)
union char5_float { // 8
char c[5]; // occupies 5 bytes
float f; // occupies 4 bytes, imposes alignment 4
};
// [c - Padding in union is present or not - Stack Overflow](https://stackoverflow.com/questions/16749343/padding-in-union-is-present-or-not)
union char9_double {
char arr[sizeof (double) + 1];
double d;
};
// [c - sizeof union larger than expected. how does type alignment take place here? - Stack Overflow](https://stackoverflow.com/questions/8453881/sizeof-union-larger-than-expected-how-does-type-alignment-take-place-here?rq=1)
struct p_int {
int *i;
};
struct int_int {
int i, j;
};
union u1 { // 8
struct {
int *i;
} s1;
struct {
int i, j;
} s2;
};
struct p_int_int {
int *i, j;
};
union u2 { // 16
struct {
int *i, j;
} s1;
struct {
int i, j;
} s2;
};
输出
CXCursor_UnionDecl: int_char [4]
CXCursor_UnionDecl: char_char [1]
CXCursor_UnionDecl: char10 [10]
CXCursor_UnionDecl: char13 [13]
CXCursor_UnionDecl: int_char13 [16]
CXCursor_UnionDecl: char5_float [8]
CXCursor_UnionDecl: char9_double [16]
CXCursor_StructDecl: p_int [8]
CXCursor_StructDecl: int_int [8]
CXCursor_UnionDecl: u1 [8]
CXCursor_StructDecl: p_int_int [16]
CXCursor_UnionDecl: u2 [16]