Void pointers

Alex via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon May 16 13:39:00 PDT 2016


Hi all!
Let's talk about void pointers a little bit. Found this already
http://forum.dlang.org/thread/codoixfeqstvqswirsax@forum.dlang.org?page=1
but my question/problem differs from the above, so maybe, I have 
found a useful application  for void pointers...

Form of the posting: I have some questions about the usage of 
void pointers in some expressions, but I'm not even sure, if void 
pointers should be used. For the latter part, I found at least 
two other possibilities, which goes further below.

Say I have something like that:

// This function is intentionally templated, as it should take 
slices and return something
// boundchecked only
@nogc T[] getSlice(T)(T* ptr, size_t a, size_t b)
{
     return T[a .. b];
}

void main()
{
     void* ptr; // this will stay uninitialized during the whole 
program run

     // something that works as desired:
     writeln(&ptr[4]); // prints '4'
     auto b = getSlice(ptr, 5, 10);
     writeln("b first: ", &b[0]); // prints '5'. This is the most 
useful feature.
     assert(b.capacity == 0); // holds always. So, getSlice 
returns always a slice, not an array.
     // arr[3] = ... // fails. It is intended to do so.

     // something that does not worked as expected:
     // how to rewrite a for loop
     for(auto i = 0; i < b.length; i++) writeln(&b[i]);
     // into a foreach loop?

     // a question about usability: is there a trait, which can 
semantically check, if a type
     // (void, or something else) behaves in the described manner?
}

Something, which also could be used to achieve the same behavior:
using ubyte* instead of void*
using something like this:
struct M
{
     @disable this();
     @disable this(this);
}

The important thing, as I found out is: the underlying type has 
to be only as large as a byte.

Background:
is already written and could be provided :)

Thanks in advance :)


More information about the Digitalmars-d-learn mailing list