GNOME Bugzilla – Bug 777194
Allow casting structs to arrays without address-of operator
Last modified: 2017-02-12 18:46:37 UTC
With file and stream operations it is common to use uint8[] as a buffer. For example see GLib.FileStream and GIO's InputStream and OutputStream. The following code works: struct Foo { public double x; public double y; public double z; } void main () { Foo bar = { 200.0, 3.0, 10.1 }; print ("Field from original struct, bar.x: %f\n", bar.x); unowned uint8[] buffer = (uint8[])&bar; unowned Foo[] result = (Foo[]) buffer; print ("Value after struct buffered and unbuffered: %f\n", (result[0].x)); } but the line: unowned uint8[] buffer = (uint8[])&bar; is not very Vala like because of the use of the address-of operator. A more Vala like syntax would be: unowned uint8[] buffer = (uint8[])bar; This change line currently produces an error from the C compiler: cannot convert to a pointer type buffer = (guint8*) _tmp3_; Vala should either produce an error that a value type cannot be cast to an array without the address-of operator or cast the value type properly in the resulting C code.
valac should report an error for the second case. Implicit address-of would be inconsistent.
Created attachment 343406 [details] [review] codegen: Support casting arbitary value-types to arrays Also calculate a valid length for the resulting array. This enables easier usage of common uint8[]-based buffer API.
@jürg: Being able to omit the adress-operator seems more natural. The difference between "Struct" and "Struct?" is not that obvious for a vala-user while *only* the former requires the pointer-syntax.
Attachment 343406 [details] pushed as 5f31633 - codegen: Support casting arbitary value-types to arrays