Thread overview
Using C's fread/fwrite with File objects
Oct 22, 2015
pineapple
Oct 22, 2015
pineapple
Oct 22, 2015
Ali Çehreli
Oct 22, 2015
pineapple
Oct 22, 2015
John Colvin
October 22, 2015
I'd like to use fread and fwrite in place of File.rawRead and File.rawWrite which force the creation of an array where I'd rather specify a buffer location and length. I'd like to do this using a File object but the handle for the C stream is a private member and I can't find any way to access it. Is there a getter or something I missed, or else some way to pry private data like this out of a class?
October 22, 2015
Answered my own question: Turns out File.getFP() does exactly what I needed
October 22, 2015
On 10/22/2015 11:20 AM, pineapple wrote:
> I'd like to use fread and fwrite in place of File.rawRead and
> File.rawWrite which force the creation of an array where I'd rather
> specify a buffer location and length.

Would you not create that buffer? :)

If you already have a piece of memory, it is trivial to convert it to a slice in D:

  auto slice = existing_pointer[0 .. number_of_elements];


http://ddili.org/ders/d.en/pointers.html#ix_pointers.slice%20from%20pointer

The operation is not expensive because D slices are nothing but a pointer and length.

Ali

October 22, 2015
On Thursday, 22 October 2015 at 18:20:07 UTC, pineapple wrote:
> I'd like to use fread and fwrite in place of File.rawRead and File.rawWrite which force the creation of an array where I'd rather specify a buffer location and length.

D's arrays *are* just buffer locations and lengths with a few extra properties, methods and operators.

T* ptrToBuffer = /* ... */;
size_t lengthOfBuffer = /* ... */;
T[] buffer = ptrToBuffer[0 .. lengthOfBuffer];
File f = /* ... */;
T[] filledPartOfBuffer = f.rawRead(buffer);

Note that at no point in the above is a new buffer allocated.
October 22, 2015
On Thursday, 22 October 2015 at 18:28:50 UTC, Ali Çehreli wrote:
> If you already have a piece of memory, it is trivial to convert it to a slice in D:
>
>   auto slice = existing_pointer[0 .. number_of_elements];
>
>
> http://ddili.org/ders/d.en/pointers.html#ix_pointers.slice%20from%20pointer
>
> The operation is not expensive because D slices are nothing but a pointer and length.
>
> Ali

Cool, I hadn't realized slices worked like that. Still, it was more convenient to use fread and fwrite in this case. I had an pointer where I wanted to be able to read and write one byte at a time and fread/fwrite are familiar and comfortable options to me.