Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
28486 Discussions

passing pointer between fortran and C

Rob1
Beginner
1,078 Views

I have a C library which is called from fortran.  The C lib creates a class and passes a pointer to it back to fortran.  The fortran program will then pass the pointer back into the C lib later on.  The problem is the class member values assigned in C are lost in communication somewhere.

I've built test projects that recreate my problem:

// testc.h
class meclass
{
public:
       meclass();
       ~meclass();
private:
       int thing1;
       int thing2;
       double thing3;
};
// testc.cpp
#include "testc.h"
meclass::meclass()
{
       thing1 = 1;
       thing2 = 4;
       thing3 = 9.0;
}
extern "C" void* funka()
{
       meclass* plop = new meclass;
       return (void*)plop;
}
extern "C" int funkb(void* plep)
{
       meclass* plup = reinterpret_cast<meclass*>(plep);      //Is static cast ok?
       return 1;
}
PROGRAM test
USE, INTRINSIC :: ISO_C_BINDING
IMPLICIT NONE
INTERFACE
       TYPE(C_PTR) FUNCTION funka() BIND(C, NAME='funka')
              USE, INTRINSIC :: ISO_C_BINDING
              IMPLICIT NONE
       ENDFUNCTION funka
       INTEGER(C_INT) FUNCTION funkb(plep) BIND(C, NAME='funkb')
              USE, INTRINSIC :: ISO_C_BINDING
              IMPLICIT NONE
              TYPE(C_PTR), INTENT(IN) :: plep
       ENDFUNCTION funkb
ENDINTERFACE
TYPE(C_PTR) LHSa                                ! result from call to funka
INTEGER(C_INT) LHSb                             ! result from call to funkb

LHSa = funka()
LHSb = funkb(LHSa)
write(*,*) 'the end'
read(*,*)

ENDPROGRAM test

When I run it and break in testc.cpp, i see the correct values for 'plop' in the call to funka:

funka.png

Then in the call to funkb the values are lost in 'plup':

funkb.png

I'm not sure where things are going wrong.  Any ideas?

thanks,

rob

0 Kudos
1 Reply
Rob1
Beginner
1,078 Views

Of course minutes after i post i discover the problem.

I changed:

TYPE(C_PTR), INTENT(IN) :: plep

to

TYPE(C_PTR), VALUE, INTENT(IN) :: plep

And it appears to work.

Thanks me!

0 Kudos
Reply