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

Function Pointer used in type

newrud
Beginner
672 Views
Hello I have a problem. I want to use a function pointer as a member in a type definition. The idea is to build a struct how its done in following code written in C:

#include
#include

typedef double Ptr(double *);

typedef struct
{
Ptr *func;
} MyStruct;

double lineareGleichung(double *x)
{
double slope;

slope = 2.0;

return slope*(*x);
}

int main(void)
{
double res, val;
int i;
MyStruct *ex = malloc(sizeof *ex);

if(ex != NULL)
{
ex->func = lineareGleichung;

for(i=0; i<5; i++)
{
val = i*0.5;
res = ex->func(&val);
printf("f(%lf) = %lf\\n", i*0.5, res);
}

free(ex);
}

return 0;
}


The following code, i wrote, is not working:

module test

implicit none

type functionPointer

contains
procedure(), pointer :: f
end type functionPointer

interface
subroutine f(x,y)
double precision :: x, y
end subroutine f
end interface

end module test

program functionPointerBsp

use test

implicit none

type(functionPointer):: FP
double precision :: x,y
integer :: i

FP%f => null()
FP%f => lineareGleichung

do i=1,5
x = i*0.5
call FP%f(x,y)
write(*,*) "F(",x,") = ", y
end do

contains
subroutine lineareGleichung(x,y)
double precision :: x, y, slope

slope = 2.d0

y = slope*x
end subroutine lineareGleichung

end program functionPointerBsp

The error is as follows:

error #8257: This is not a valid attribute for the type bound procedure definition statement. [POINTER]
procedure(), pointer :: f
-----------------^
module.f90(12): error #8262: The passed-object dummy argument must be dummy data object with the same declared type as the type being defined.
subroutine f(x,y)
-----------------^

Does anyone have an idea how to solve the problem?

0 Kudos
1 Reply
Steven_L_Intel1
Employee
672 Views
You are very close.

The CONTAINS in the TYPE declaration is not what you want - this means that the things that follow are type-bound procedures. You simply want a procedure pointer component of the derived type. So initially, the CONTAINS is removed.

But then there is the following rule in the standard: "C453 If the procedure pointer component has an implicit interface or no arguments, NOPASS shall be specified." So after removing CONTAINS, replace the line that follows with this:

procedure(),nopass, pointer :: f

This works.
0 Kudos
Reply