Re: [Vala] Question regarding passing a strings as arguments to a method



If one has a look at the C code generated by Vala for the following
two examples, it appears that the "unowned" keyword has no influence
on the way
the string b (of type gchar*) is passed to f().

In both cases, it is passed as a pointer (without duplication).

Therefore it seems to me that the Vala tutorial is slightly misleading
and should read:


- "In Vala strings are always passed by address".


(of course some will argue that the address itself is passed by value,
but that is not the point, the fact is that it looks as if the passing
of string types as arguments to a function not not generate a copy in
Vala).

Serge.
(See examples hereunder)


$cat pass_string1.c pass_string.c

////
using Posix;

void f(string s) {
        printf("%s\n", s);
}

void main(string[] argv) {
        unowned string a = "hello";
        unowned string b = a;
        f(b);
}

/////
using Posix;

void f(string s) {
        printf("%s\n", s);
}

void main(string[] argv) {
        string a = "hello";
        unowned string b = a;
        f(b);
}
////

$diff pass_string1.c pass_string.c

< /* pass_string1.c generated by valac 0.13.1, the Vala compiler
<  * generated from pass_string1.vala, do not modify */
---
/* pass_string.c generated by valac 0.13.1, the Vala compiler
 * generated from pass_string.vala, do not modify */
10a11
#define _g_free0(var) (var = (g_free (var), NULL))
25c26,27
<       const gchar* a;
---
      gchar* _tmp0_;
      gchar* a;
27c29,30
<       a = "hello";
---
      _tmp0_ = g_strdup ("hello");
      a = _tmp0_;
29a33
      _g_free0 (a);







2011/7/11 Гаврилов Максим <ulltor gmail com>:
Strings are passed by value. To avoid this use "unowned" keyword.

11.07.2011 1:36 пользователь "Serge Hulne" <serge hulne gmail com> написал:
The Vala tutorial says:
"*Parameter Directions* **

*A method in Vala is passed zero or more arguments. The default behaviour
when a method is called is as follows: *

- *Any value type parameters are copied to a location local to the method
as it executes. *
- *Any reference type parameters are not copied, instead just a reference
to them is passed to the method. *

*This behaviour can be changed with the modifiers 'ref' and 'out'.* "


*My question therefore is:*

- are strings passed by value or by reference to methods (by default).
- is it possible to pass a string by reference to a method (to avoid
duplication)

Serge.




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]