Copying Variants
In addition to VariantCopyInd, f90VB offers subroutine VariantCopy, which produces a traditional copy of a Variant variable. If the Variant variable contains a Safe Array or a BString, the contained Safe Array or BString is replicated. If the Variant contains a reference to an object interface (i.e. the variant is of type VT_UNKNOWN or VT_DISPATCH) then the reference counter of the interface is incremented (through a call to the interface’s AddRef procedure). Example 3.2 shows how VariantCopy can be used to duplicate a Variant containing a Safe Array.
Example 3.2
!Replicates a Variant containing a Safe Array
use f90VBDefs
use f90VBSafeArrays
use f90VBVariants
implicit none
type(VARIANT)::vrOrig, vrCopy
integer::i,j
real(FLOAT_KIND),pointer,dimension(:,:)::MappedArray
real(FLOAT_KIND),dimension(5,4)::AFortranArray
integer(SAFEARRAY_KIND)::SAHndl
integer(HRESULT_KIND)::iRet
!Fill AFortran Array with random numbers
call random_seed
call random_number(AFortranArray)
!Generate a new safe array using f90VB's
!automatic array creation facilities
call SafeArrayCreate(SAHndl,VT_R4, AFortranArray)
!Create a variant with a Safe Array
!Note that the Safe Array contained in this variant
!is a copy of the Safe Array in SAHndl. Their values
!are the same, but they are not the same Safe Array
vrOrig = VariantCreate(VT_ARRAY+VT_R4,SAHndl,iRet, VT_ARRAY+VT_R4)
!we don't need SAHndl anymore, so we can destroy it
call SafeArrayDestroy(SAHndl)
!map Safe Array in vrOrig to easily print its values
call SafeArrayAccessData(vrOrig%varVal%parray,MappedArray,iRet)
!print values in the safe array
print *,'Values of Safe Array in vrOrig:'
do i=lbound(MappedArray,1),ubound(MappedArray,1)
print *,(MappedArray(i,j),j=lbound(MappedArray,2),ubound(MappedArray,2))
enddo
print *,''
!Copy vrOrig to vrCopy
call VariantCopy(vrOrig,vrCopy)
!map Safe Array in vrOrig to easily print its values
call SafeArrayAccessData(vrOrig%varVal%parray,MappedArray,iRet)
!print values in the safe array
print *,'Values of Safe Array in vrCopy:'
do i=lbound(MappedArray,1),ubound(MappedArray,1)
print *,(MappedArray(i,j),j=lbound(MappedArray,2),ubound(MappedArray,2))
enddo
print *,''
!Destroy the variants, making sure their contents are
!also destroyed and memory is released (this is an
!important step, particularly when the variant contains
!a type that allocates system resources, like Safe Arrays,
!BStrings or object references)
call VariantClear(vrOrig)
call VariantClear(vrCopy)
stop
end