std.stream.File help required (and classes)

Ali Çehreli acehreli at yahoo.com
Tue Mar 27 14:51:38 PDT 2012


On 03/27/2012 02:20 PM, akaz wrote:

 > what is the equivalent of
 > std.stream.File.writeBlock(const void* buffer, size_t size)? I see there
 > is a std.stdio.rawWrite(T)(in T[] buffer);
 >
 > But, my data is: a (byte*) pointer and a length. How do I write
 > something like
 > std.stream.File.writeblock(cast(byte*)p,cast(int)len) using
 > std.stdio.File.rawWrite?

D has this helpful syntax of treating a raw pointer as a slice. Note 
p[0..length] below:

import std.stdio;

void main()
{
     byte[] bytes = [ 81, 82, 83, 84, 85 ];

     byte * p = &(bytes[1]);
     size_t length = 3;

     auto file = File("raw_written_bytes", "w");
     file.rawWrite(p[0..length]);
}

 > Yes, that should be the case. f is the mother structure (a pointer
 > towards a MSFilter structure) that should never disappear and f.data
 > should not be assigned somewhere else.

How is all that memory allocated?

 > I still cannot grasp
 > that fundamental thing when a class instance is a variable and when it
 > is a pointer

If you don't mind, your code has way too many pointers. :) As a person 
coming from C++, here is how I made sense of it:

   auto var = new MyClass();

The line above has two entities:

1) An anonymous MyClass object on the right-hand side which belongs to 
the runtime. It will be garbage collected later.

2) The 'class variable' on the left-hand side. This is the handle to 
that object. You can think of this as being implemented as a pointer 
behind the scene, but there is no pointer in D with classes.

To complicate matters, you can spell out the type of 'var':

   MyClass var = new MyClass();

Very confusing, but the actual types of the left-hand and right-hand 
sides are still different: "class variable" vs. "class object".

 > ; when is T x;

Prefer that one until it doesn't compile. :)

 > and when is T* x = new T();

That is needed when T is a value type (e.g. a struct) and that you want 
to handle its lifetime manually.

 > or, when is T* x=(T*)calloc(1,sizeof(T));)

Since calloc() is a C library function, you must use a T* there.

Speaking of which, is f.data in such a memory that GC is not aware of? 
Then your class reference in there will not keep the File object alive. 
You must call GC.addRange() to let GC know that you have pointers into 
the GC's memory.

A better thing to do may be to call GC.calloc() from the core.memory module.

(Hmmm. Maybe I will translate this chapter next: 
http://ddili.org/ders/d/bellek_yonetimi.html )

 > I expected D to be a sort of
 > "better C with *facultative* classes" but I find it to be quite... C#.
 > Is my vision correct?

I've never used C# but I know that it has brought many good features 
from many languages. :)

Ali



More information about the Digitalmars-d-learn mailing list