我正在为一段Fortran代码编写一个mex网关。
在Fortran代码中,为便于移植,浮点变量声明为
REAL(kind(0.0D0)) :: x, y, etc(顺便说一句,我知道有更好的方法来做,就像在4 vs integer(4) vs integer(kind=4),8" mean?和https://software.intel.com/en-us/blogs/2017/03/27/doctor-fortran-in-it-takes-all-kinds上讨论的那样)
然而,在我看来,mex只支持实*8和实*4,前者是双倍的,后者是单身的。我从以下函数/子程序中得到了这样的印象:
mxIsDouble,mxIsSingle,mxCopyPtrToReal8,mxCopyReal8ToPtr,mxCopyPtrToReal4,mxCopyReal4ToPtr
我的问题如下。
甚至是
integer, parameter :: dp = selected_real_kind(15, 307)
real(kind=dp) :: x, y, etc还是我应该简单地声明
REAL*8 :: x, y, etc 下面的代码是一个示例。请参见x、y和xs的声明。
#include "fintrf.h"
subroutine mexFunction(nlhs, plhs, nrhs, prhs)
C y = square (x)
C x: a floating point scalar
C y: x^2
implicit none
C mexFunction arguments
integer, intent(in) :: nlhs, nrhs
mwPointer, intent(in) :: prhs(nrhs)
mwPointer, intent(inout) :: plhs(nlhs)
C function declarations:
mwPointer, external :: mxCreateDoubleScalar, mxGetPr
mwSize, external :: mxGetM, mxGetN
integer*4, external :: mxIsDouble, mxIsSingle
C variables
mwSize, parameter :: mwOne = 1
integer, parameter :: dKind = kind(0.0D0)
integer, parameter :: sKind = kind(0.0)
real(kind=dKind) :: x, y ! Does this improve the portablity?
real(kind=sKind) :: xs ! Does this improve the portablity?
C validate number of arguments
if (nrhs .ne. 1) then
call mexErrMsgIdAndTxt ('mex:nInput', '1 input required.')
endif
if (nlhs .gt. 1) then
call mexErrMsgIdAndTxt ('mex:nOutput', 'At most 1 output.')
endif
C validate input
if (mxIsDouble(prhs(1)) .ne. 1 .and. mxIsSingle(prhs(1)) .ne. 1)
! What if the input is a floating point number but neither Double nor Single?
+ then
call mexErrMsgIdAndTxt ('mex:Input', 'Input a real number.')
endif
if (mxGetM(prhs(1)) .ne. 1 .or. mxGetN(prhs(1)) .ne. 1) then
call mexErrMsgIdAndTxt ('mex:Input', 'Input a scalar.')
endif
C read input
if (mxIsDouble(prhs(1)) .eq. 1) then
call mxCopyPtrToReal8(mxGetPr(prhs(1)), x, mwOne)
else
call mxCopyPtrToReal4(mxGetPr(prhs(1)), xs, mwOne)
x = real(xs, dKind)
! What if the input is a floating point number but neither REAL*8 nor REAL*4
endif
C do the calculation
y = x**2
C write output
plhs(1) = mxCreateDoubleScalar(y)
return
end subroutine mexFunction代码运行正常。但我不确定它是否可携带。
发布于 2019-07-28 23:39:56
REAL*4和REAL*8是非标准和不可携带的.REAL(KIND(0.0D0)在每个平台上都为您提供DOUBLE PRECISION,这是Fortran标准所要求的。
我不能和MEX网关说话,但是你应该避免明显的非标准特性。
一个流行的选择是定义一个模块,该模块为正在使用的类型声明命名(参数)常量。例如:
module kinds integer, parameter :: SP = KIND(0.0) integer, parameter :: DP = KIND(0.0D0) end module kinds
然后可以使用SP和DP作为类值。如果您需要更改这些内容,只需编辑模块即可。
发布于 2019-09-11 16:33:09
目前,无论您将变量定义为实*8/实*4还是实(REAL64)/REAL(REAL32),都没有区别。将来,MathWorks可能会出现并重写它们的函数以使用可移植变量声明,但在我看来,这是不太可能的,因为很多原因。
如果您查看fintrf.h文件(包括在每个Fortran网关源文件中),您将看到所有特定于MEX的过程都定义为“星号符号”,例如# define MWPOINTER INTEGER*8。因此,即使使用iso_fortran_env或selected_real_kind中的类型定义所有变量,只要使用MathWorks变量类型,仍然使用“星号符号”类型,除非您使用所选的类型规范来遍历该头文件并重新定义每个符号。
https://stackoverflow.com/questions/57244555
复制相似问题