问题
I'd like to have a kind of diffptr_t in fortran with iso_c_bindings. The memory distance result must be a signed int.
type(c_ptr) :: start,ref
type(c_int) :: res
start=c_loc(my_struct%a)
ref=c_loc(my_struct%b%c)
res=start-ref
Compilation error:
This binary operation is invalid for this data type.
An arithmetic or LOGICAL type is required in this context.
Thanks
回答1:
You cannot do pointer arithmetic in standard Fortran. You have to rely on the processor dependent binary correspondence between pointers and integers.
Also, there are no unsigned integers in Fortran.
type(c_ptr) :: start,ref
integer(c_int) :: res
start = c_loc(my_struct%a)
ref = c_loc(my_struct%b%c)
res = int( transfer(start, 1_c_intptr_t) - transfer(ref, 1_c_intptr_t) , c_int)
There may be problems, if the pointer values are larger, than the maximum positive value for the signed c_intptr_t
.
来源:https://stackoverflow.com/questions/19926504/diffptr-t-fortran-with-iso-c-bindings