Re: C Struct Support
- Posted by raseunew Dec 30, 2010
- 1835 views
here's my first take on C structure support
cstruct.e namespace cstruct /* reserved structure primitive names (need associated byte sizes) */ int8 int16 int32 int64 uint8 uint16 uint32 uint64 float double byte char ubyte uchar word dword longlong pointer struct --// public type = atom --// create new memstruct public function new(sequence ns_struct) return allocate(sizeof(ns_struct)) end function /* string */ mem_struct c_str pointer( integer( 8, array, null_terminated ) ) chars end mem_struct /* wide string */ mem_struct wc_str pointer( integer( 16, array, null_terminated ) ) wchars end mem_struct /* allocate array of [n] items expands to TYPE(TYPESIZE, array, N) n */ mem_struct vector[N, TYPE=int32] TYPE[N] v end mem_struct usage : basic.e namespace basic include cstruct.e as cs /* person structure */ mem_struct person cs:uchar[32] name null_terminated cs:int32 age cs:c_str company cs:wc_str address1 end mem_struct usage 2: test.e include cstruct.e as cs include basic.e as basic /* array of int32 expands to integer(32, array, 10) */ cs:struct A = cs:new(basic:vector[10]) /* array of int64 expands to integer(64, array, 10) */ cs:struct B = cs:new(basic:vector[10, cs:int64]) --// single person cs:struct P = cs:new(basic:person()) --// assignment P.basic.person.name = cs:string("My Name") P.basic:person.age = 44 P.basic.person.company = cs:string("My Company") P.basic.person.address1 = cs:w_string("My Address") --// pointer dereferencing printf(1, "name = %s\n", { P.basic:person.name.* }) printf(1, "age = %d\n", { P.basic:person.age }) printf(1, "company = %s\n", { P.basic:person.company.* }) printf(1, "address1 = %s\n", { P.basic:person.address1.wchars }) --// pointer address @ printf(1, "pointer address = %d\n", { @P.basic:person.name }) --// array of persons cs:struct D = cs:new(basic:vector[10, basic:person()]) /* vector/array indexing instance . [idx] */ cs:struct E = cs:new(basic:vector[10]) for i = 0 to 9 do --// implicit v member access E.[i] = i --// explicit v member access E.v[i] = i end for