[Date Prev] [Date Next] [Thread Prev] [Thread Next] Date Index Thread Index Search archive:
Date:Mon May 23 08:17:40 2002 
Subject:Re: returning pointers 
From:Jonathan L Cunningham 
Volume-ID:1020423.02 

On Tue, 14 May 2002 12:22:39 +0000 (UTC), mhl@Cs.Nott.AC.UK said:

>I know how to pass and return a pointer of specific type from C to 
>poplog for example,
>
>external declare test in c;
>        int *foo(x);
>            int *x;  
>            {}
>endexternal;
>
>external load test;
>        'external.so'
>endexternal;
>
>Which may correspond to a C function (in external.so)
>
>int *foo(int *x)
>{
>  int *y;
>  int z;
> 
>  z=(*x)+4;
>  y=&z;
>  return y;
>}
>
>Is there a way to return arbitary (unspecified type) pointers? For 
>example would it be possible to return a pointer to a C++ class?

I presume you mean a pointer to an object, since there are no pointers
to C++ classes. (In case that is not clear:

   class example { int rhubarb; }

defines a class called example, but there is nothing corresponding to
the class that exists at run-time, so you can't have a pointer to it.

You can create an instance of the class:

  example e1;

declares e1 as an instance of example, and e1.rhubarb is an int.

You can have a pointer to e1, e.g.

  example pe1 = &e1;

In answer to the other part of your question, the usual way to pass
around unspecified pointers is to cast them to pointer-to-void, e.g.

 v = (void*)pe1

I don't know whether the external mechanism in poplog supports
pointers to void, but if it does, you can then pass the pointer
back to C++, and cast it back to the correct type, e.g.

 (example*)v

will cast v back. If you intend to do this, it would be better to
use the C++ RTTI (run time type information) and use a dynamic cast,

  dynamic_cast<example*>(v)

However, it is generally a *bad* idea to pass around void pointers
and there is often a better solution. Without knowing more about
your problem, I can't guess what the better solution might be. And,
sometimes - just sometimes - the void pointers are the best solution
(that's why they are allowed).

HTH,
  Jonathan

-- 
Jonathan Cunningham
(r.a.sf.c backlog currently c. 500 posts)