Generic functions to convert to void* and from void*

Daniel Keep daniel.keep.lists at gmail.com
Sun Feb 22 15:28:09 PST 2009



TSalm wrote:
> 
>> I'm trying to build function which have the hability to convert a type
>> to void* and from void*.

First of all, I have to ask: have you looked at std.variant /
tango.core.Variant?

>> I must use "ref" in the "toPtr" function because of this :
>> http://www.digitalmars.com/pnews/read.php?server=news.digitalmars.com&group=digitalmars.D.learn&artnum=15600
>>
>>
>> Do you think that what I done is correct ?
>>
>>
>> /* --------- CODE --------- */
>>
>> /***
>>   * Convert a value to a void*
>>   * Params:
>>   *     val =
>>   * Returns:
>>   */
>> void* toPtr(T)(ref T val)
>> {
>>    void* p ;
>>
>>    static if ( is( T b : Type ) )

What is this test doing?  You're checking to see if T can be implicitly
cast to "Type"... but "Type" isn't defined.  And what is 'b' doing there?

>>    {
>>      p = new T ;
>>      p = &val ;

You never use the freshly-allocated T.  You assign it to p and then
immediately overwrite it with &val.

>>    }
>>    else
>>    {
>>      p = &val ;
>>    }
>>
>>    return p ;
>> }

So the function is basically doing this:

T fromPtr(T)(ref T val)
{
    return &val;
}

>> /***
>>   * Convert a void* to his value
>>   * Params:
>>   *     ptr =
>>   * Returns:
>>   */
>> T fromPtr(T)(void* ptr)
>> {
>>    return *(cast(T*)ptr) ;
>> }
>> /* ------- END CODE -------- */
>>
> 
> I've forget to say that toPtr can't be call with constants.

I get the distinct impression that you're seriously over-thinking this.
 Both of these functions could be rewritten as casts.  Aside from that,
you've given no context for me to have any idea what you're trying to
accomplish here.

  -- Daniel


More information about the Digitalmars-d-learn mailing list