Jack Scheible said:
> Is it possible to convert a pointer to one derived type into a pointer
> to another derived type? TRANSFER seems to return an object of the
> derived type, rather that a pointer to an object of the derived type,
> even if the MOLD is a pointer. What gives?
What gives is that:
(1) in pointer context, pointer names refer to the pointer itself
(2) in non-pointer context, pointer names refer to the target
Pointer context means:
(i) pointer assignment
(ii) allocate
(iii) deallocate
(iv) passing to a pointer dummy argument
Since MOLD is not a pointer dummy argument, it is the target which is
referenced.
To avoid the automatic dereferencing and do something to the pointer itself,
you need to wrap it up in a derived type.
e.g.
TYPE MYTYPE
... this is the derived-type we want a pointer to.
END TYPE
TYPE MYTYPE_PTR
TYPE(MYTYPE),POINTER :: P
END TYPE
Then given
TYPE(MYTYPE),TARGET :: X
TYPE(MYTYPE),POINTER :: P1
TYPE(MYTYPE_PTR) :: P2,P3(1)
P1 => X
P2%P => X
We now have
(a) TRANSFER(X,(/42/))
is the contents of X "transferred" into an integer array
(b) TRANSFER(P1,(/42/))
is also the contents of X "transferred" into an integer array, since
P1's target is X
(c) TRANSFER(P2,(/42/))
is the contents of P2 (a pointer to X) "transferred" into an integer
array; note that this might well be more than just an address, there
might be other information stored in the pointer as well.
In particular, given an array of MYTYPE_PTR's, e.g.
P3(1)%P => X
Then
TRANSFER(TRANSFER(P2,(/42/)),P3,SIZE(P3))
is just the same as P3, i.e. the pointer(s) are transferred intact.
However, if we have two different derived types and wrapped-up pointers to
them, e.g.
TYPE mytype_1
...
END TYPE
TYPE mytype_2
...
END TYPE
TYPE mytype_1_ptr
TYPE(mytype_1),POINTER :: p
END TYPE
TYPE mytype_2_ptr
TYPE(mytype_2),POINTER :: p
END TYPE
TYPE(mytype_1),TARGET :: T
TYPE(mytype_1_ptr) X
TYPE(mytype_2_ptr) Y
Then
X%p => T
Y = TRANSFER(X,Y)
X = TRANSFER(Y,X)
At this point X is not well-defined; if X and Y are the same size, X%p will
still point to T - however this is NOT guaranteed by the standard. It is
quite conceivable that X and Y will be different sizes, i.e. that pointers
are not always the same size.
It is also not guaranteed that "similar" derived types will be laid out in
memory in anything like a similar way, so it is not advisable to attempt to
simulate C "union" types using (too-)clever tricks like TRANSFER of pointers.
Cheers,
--
...........................Malcolm Cohen, NAG Ltd., Oxford, U.K.
([log in to unmask])
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|