determining if a void* points to a valid Object

nobody nobody at mailinator.com
Thu Aug 17 15:14:28 PDT 2006


Luís Marques wrote:
> Hello all,
> 
> I'm making a transition of a code base from C to D. I wish to alleviate 
> the transition by making it gradual, but that requires being able to 
> distinguish D Objects from the existing C structs, given a pointer.
> 
> Could you help me with this please?
> 
> 1. You have a "void *ptr".
> 2. You have a struct NotDObject whose declaration you can control. (e.g. 
> add fields and require that they possess certain values)
> 
> How do you determine with fairly good reliability if ptr points to an 
> Object or to a NotDObject struct?
> 
> You are allowed to assume that DMD/GDC is used, and even a specific 
> version of that compiler. I don't care much if it is a kludge (it's a 
> temporary solution), but extra points if you can make it implementation 
> independent.
> 
> Thanks a lot,
> Luís Marques

D Application Binary Interface
http://digitalmars.com/d/class.html

Classes
An object consists of:

offset 	contents
0 	pointer to vtable
4 	monitor
8... 	non-static members


I think if I understand your question correctly then I believe what you can do 
if first assert( ptr !is null ). Now if I can define NotDObject and initialize 
the members I would do the following:


   struct NotDObject
   {
     int reserveredA = 0;
     int reserveredB = 0;
     // anything you want follows here
   }

Now since we know ptr is not null then it it points to a NotDObject then 
dereferencing the pointer should give us a null value. Otherwise we now have a 
pointer to the vtable from the D ABI above.

   if((*(cast(void*)) is null ) // NotDObject
   else                         // Object



More information about the Digitalmars-d mailing list