www.digitalmars.com         C & C++   DMDScript  

D - C trick possible in D?

reply "Ben Hinkle" <bhinkle4 juno.com> writes:
Here is a C trick that I haven't been able to translate to D. I came across
it when translating the C header for gmp.
Consider the following C code:

  typedef struct {int a,b;} A;
  typedef A[1] A_t;
  void bar(A*);
  void foo(void) {
    A_t x;
    bar(x);
  }

The function foo allocates stack space sizeof(A) for x since A_t is an array
of length 1 of A. So it looks in foo like x is being passed around "by
value". But since arrays can be converted to pointers freely the function
bar is called with x being passed "by reference". Is there any way to get
this same trick with D purely by typedefs and/or aliases? I want the code in
foo to look the same in C and in D.

My current solution is to force users to write D code that explicitly takes
the address of x to pass to bar. This is more standard anyway and it annoys
me when you can't tell from a type what kind of copy semantics it has. So my
translation of the above would be

  struct A {int a,b;};
  alias A A_t;
  void bar(A*);
  void foo(void) {
    A_t x;
    bar(&x);
  }

thoughts?
-Ben
Sep 06 2003
parent Farmer <itsFarmer. freenet.de> writes:
To get rid of the addressof operator you could use the inout attribute in
function bar: So the code becomes: 

   struct A {int a,b;};
   alias A A_t;
   void bar(inout A);
   void foo(void) {
     A_t x;
     bar(x);
   }


But I like your initial translation somewhat more, too. Because when I
look at the line 
     bar(x);
I can't see that x is passed by reference. Except when a super smart IDE
uses syntax highlighting for that. 


Farmer.


"Ben Hinkle" <bhinkle4 juno.com> wrote in
news:bjeafl$1fkf$1 digitaldaemon.com: 

 Here is a C trick that I haven't been able to translate to D. I came
 across it when translating the C header for gmp.
 Consider the following C code:
 
   typedef struct {int a,b;} A;
   typedef A[1] A_t;
   void bar(A*);
   void foo(void) {
     A_t x;
     bar(x);
   }
 
 The function foo allocates stack space sizeof(A) for x since A_t is an
 array of length 1 of A. So it looks in foo like x is being passed around
 "by value". But since arrays can be converted to pointers freely the
 function bar is called with x being passed "by reference". Is there any
 way to get this same trick with D purely by typedefs and/or aliases? I
 want the code in foo to look the same in C and in D.
 
 My current solution is to force users to write D code that explicitly
 takes the address of x to pass to bar. This is more standard anyway and
 it annoys me when you can't tell from a type what kind of copy semantics
 it has. So my translation of the above would be
 
   struct A {int a,b;};
   alias A A_t;
   void bar(A*);
   void foo(void) {
     A_t x;
     bar(&x);
   }
 
 thoughts?
 -Ben
 
 
Sep 07 2003