This is the mail archive of the fortran@gcc.gnu.org mailing list for the GNU Fortran project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Possible c_ptr bug with gfortran 4.5.0 20090903 (experimental) [trunk revision 151392]


Hi Dennis,

Many thanks indeed for your quick response, and for kindly pointing out my error. That's certainly a bit of a gotcha for a C-Fortran interfacing novice like me, but one I shall remember in future! As you suggest, my code runs fine when I add the 'value' attribute - I agree that this is the preferable approach, as it keeps the C code idiomatic.

Thanks again,

Ian

Dennis Wassel wrote:
Hi Ian,

I have had problems with passing pointers from C to Fortran and back again. This might be a bug, but of course I might be doing something silly.

I skimmed your code and I think you are indeed, but I also think there is little shame in falling into this particular trap. Been there, done it myself!

Pointer location: 22040480
Value: 352
Pointer location (Fortran):             22040480
Pointer location: -47467344
Value: 22040480

Clearly at some point, pointer and value get mixed up here. What the C caller does is to pass a copy of the pointer to the function, so the callee is supposed to receive the pointer by value -- meaning the value of the pointer variable, not the value of the object it points to. Now re-read that sentence :-) The Fortran function OTOH expects to receive a c-pointer by reference*, i.e. the usual Fortran way of passing arguments (*by reference is not exactly true, but it behaves like that).

You should be able to fix your code by either passing the address of
the pointer variable (i.e. a pointer to the pointer) from C, or by
adding the VALUE attribute to the c_ptr dummy argument in Fortran, so
it expects a copy of the pointer variable, not a reference to it.
Personally, I prefer the latter option.

Cheers,
Dennis


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]