Marius
Marius

Reputation: 2273

Converting GLib.Array to built in array

Lets say I have a GLib.Array<Item?> and want to convert that into a Item[], how would I do that in Vala?

Upvotes: 2

Views: 1010

Answers (2)

meskobalazs
meskobalazs

Reputation: 16031

A naive approach would be, that you take out all the items from the array with the index() method and append them to an empty Item[] array, using +=.

A simple example program:

public int main (string[] args) {
    Array<string> array = new Array<string> ();
    array.append_val ("1. entry");
    array.append_val ("2. entry");

    string[] builtin = {};

    for (var i = 0; i < array.length; i++) {
        builtin += array.index (i);
    }

    return 0;
}

update: GLib.GenericArray really seems like a better solution. As for the data attribute: At GenericArray it is documented at Valadoc, at Array it isn't (that doesn't mean it does not work, but I haven't tried it).

Upvotes: 2

nemequ
nemequ

Reputation: 17492

First off, unless you need to for interoperability with existing code, don't use GLib.Array. Use GLib.GenericArray, which is much easier to use correctly and harder to use incorrectly.

GLib.Array.data is a regular array (Item?[] in your case), as is GLib.GenericArray.data, so you can just use that. If you assign it to an owned variable Vala will make a copy.

Upvotes: 5

Related Questions