From Berwin.Turlach at gmail.com  Tue Mar  6 14:37:03 2012
From: Berwin.Turlach at gmail.com (Berwin A Turlach)
Date: Tue, 6 Mar 2012 21:37:03 +0800
Subject: [Rd] Calling FORTRAN function from R issue?
In-Reply-To: <879BAEC9-1963-4574-B962-CA8CC9D4F13B@xs4all.nl>
References: <CADUbQ5ghmCd-3K4hx=FrzhA8YwfohhUp0-g6rJHHU0s-uEfN+A@mail.gmail.com>
	<B1B70BE3-2D8A-495B-8893-CC67026E1E9F@xs4all.nl>
	<20120306195608.7ec858c0@bossiaea>
	<879BAEC9-1963-4574-B962-CA8CC9D4F13B@xs4all.nl>
Message-ID: <20120306213703.6a5a091f@absentia>

G'day Berend,

On Tue, 6 Mar 2012 13:06:34 +0100
Berend Hasselman <bhh at xs4all.nl> wrote:

[... big snip ...]

> But I would really like to hear from an Rexpert why you
> shouldn't/can't use external here in the Fortran.

Probably less a question for an Rexpert but for a Fortran expert....

If you insert "implicit none" (one of my favourite extensions that I
always use) as the first statement after 
	subroutine callzdotc(retval,n, zx, incx, zy, incy)
you will see what is going on.  The compiler should refuse compilation
and complain that the type of zdotc was not declared (at least my
compiler does).  For FORTRAN to know that zdotc returns a double
complex you need the 
	double complex zdotc
declaration in callzdotc.

An
	external double complex zdotc
would be necessary if you were to call another subroutine/function, say
foo, that accepts functions as formal arguments and you want to pass
zdotc via such an argument.  Something like

	subroutine callzdotc(....)
        ....
        external double complex zdotc
	....
        call foo(a, b, zdotc)
        ....
	return
	end

	subroutine(a, b, h)
	double complex h, t
	....
	t = h(..,..,..,..)
	....
	return
	end

In C, the qualifier (or whatever the technical term is) "external" is
used to indicate that the function/variable/symbol is defined in
another compilation unit.  In FORTRAN77, "external" is used to tell the
compiler that you are passing a function to another
function/subroutine.  At least that is my understanding from what I
re-read in my FORTRAN documentation.
 
Thus, perhaps strangely, if there is only a 
	external double complex zdotc
declaration in your subroutine, the compiler doesn't know that a call
to zdotc will return a double complex but will assume that the result
has the implicitly defined type, a real*8 IIRC.  So zdotc is called, and
puts a double complex as result on the stack (heap?), but within
callzdotc a real as return is expected and that is taken from the
stack (heap?), that real is than coerced to a double complex when
assigned to retval.  Note that while I am pretty sure about the above,
this last paragraph is more speculative. :)  But it would explain why
the erroneous code returns 0 on little-endian machines.

HTH.

Cheers,
	
	Berwin




Cheers,

	Berwin



[Rd] Calling FORTRAN function from R issue?
Berwin A Turlach