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

Passing pointer to a heap allocation from C/C++ to FORTRAN?

rre9518
Beginner
690 Views

void CMyClass::myCallToFortran()

{

int *cintArray = (int *)malloc(100);

cintArray[0]=1;

cintArray[1]=2;

cintArray[2]=3;

int arrayCount = 100;

myfcn90(cintArray,&arrayCount);

}

Then, my FORTRAN code, which crashes when I attempt to access the array is:

subroutine fcn90(cintArray,arrayCount) bind(C,name='myfcn90')

use, intrinsic :: iso_c_binding

type(c_ptr), intent(in):: cintArray

integer*4, intent(in) ::arrayCount

integer*4, dimension(:),pointer :: a

integer i,k

call c_f_pointer(cintArray,a,(/arrayCount/))

k = a(1) <= CRASH occurs right here. Debugger shows thatthe values are "undefined Addresses". Run time error is 80010105

end subroutine

0 Kudos
4 Replies
rre9518
Beginner
690 Views
Quoting - rre9518

void CMyClass::myCallToFortran()

{

int *cintArray = (int *)malloc(100);

cintArray[0]=1;

cintArray[1]=2;

cintArray[2]=3;

int arrayCount = 100;

myfcn90(cintArray,&arrayCount);

}

Then, my FORTRAN code, which crashes when I attempt to access the array is:

subroutine fcn90(cintArray,arrayCount) bind(C,name='myfcn90')

use, intrinsic :: iso_c_binding

type(c_ptr), intent(in):: cintArray

integer*4, intent(in) ::arrayCount

integer*4, dimension(:),pointer :: a

integer i,k

call c_f_pointer(cintArray,a,(/arrayCount/))

k = a(1) <= CRASH occurs right here. Debugger shows thatthe values are "undefined Addresses". Run time error is 80010105

end subroutine


0 Kudos
rre9518
Beginner
690 Views
Quoting - rre9518

void CMyClass::myCallToFortran()

{

int *cintArray = (int *)malloc(100*sizeof(int));

cintArray[0]=1;

cintArray[1]=2;

cintArray[2]=3;

int arrayCount = 100;

myfcn90(cintArray,&arrayCount);

}

Then, my FORTRAN code, which crashes when I attempt to access the array is:

subroutine fcn90(cintArray,arrayCount) bind(C,name='myfcn90')

use, intrinsic :: iso_c_binding

type(c_ptr), intent(in):: cintArray

integer*4, intent(in) ::arrayCount

integer*4, dimension(:),pointer :: a

integer i,k

call c_f_pointer(cintArray,a,(/arrayCount/))

k = a(1) <= CRASH occurs right here. Debugger shows thatthe values are "undefined Addresses". Run time error is 80010105

end subroutine


Malloc should have read malloc(100*sizeof(int)).

I have also tried new int[100];
0 Kudos
IanH
Honored Contributor III
690 Views

You are passing the pointer out of C/C++ by value but your fortran subroutine receives it (by default) by reference. Instead:

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

An unrelated technicality is that the integers on the fortran side should have kind C_INT.

IanH
0 Kudos
rre9518
Beginner
690 Views
Thank You Ian, that did the trick.

0 Kudos
Reply