What Should I MarshalAs for Character Type in Fortran?

蹲街弑〆低调 提交于 2019-12-23 02:36:12

问题


I am calling a fortran subroutine from C#. One of the parameter I have to pass in is character .i.e, in fortran that parameter is declared as

character, intent(in)  ::  bmat*1

The issue now is, in C# code, what should I marshaled it as? I know that for integer, I should marshal it as [MarshalAs(UnmanagedType.I4)], but what about character?

Edit: This is my fortran code:

  subroutine chartest(bmat)
    !DEC$ ATTRIBUTES DLLEXPORT::chartest
    !DEC$ ATTRIBUTES ALIAS:'chartest'::chartest
    !DEC$ ATTRIBUTES VALUE ::bmat
    character, intent(in)  ::  bmat*1
    if(bmat .eq. 'G')then
        print *, bmat
    else
        print *, ' no result '
    endif
   end

And this is my interop code:

    [DllImport(@"eigensolver_win32.dll")]
    public static extern void chartest( [MarshalAs(UnmanagedType.U1)] char bmat);

This is how I call the routine:

    char bmat = 'G';
    EigenSolver32.chartest(bmat);

The result I got was "no result", indicating that the if is not fulfilled.


回答1:


The character type in FORTRAN is an unsigned 8 bit quantity.

[MarshalAs(UnmanagedType.U1)]

Will work.

The non-standard FORTRAN byte type is signed. it would be UnmanagedType.I1

Edit: C# char type is a Unicode (16 bit) type. The C# byte type is the one that matches the FORTRAN character type.

[DllImport(@"eigensolver_win32.dll")]
public static extern void chartest( [MarshalAs(UnmanagedType.U1)] byte bmat);

Also, if I remember correctly all FORTRAN function arguments are passed by reference, so you may need this instead.

[DllImport(@"eigensolver_win32.dll")]
public static extern void chartest( [MarshalAs(UnmanagedType.U1)] ref byte bmat);

And I think that [MarshalAs(UnmanagedType.U1)] is redundant for byte.



来源:https://stackoverflow.com/questions/2376585/what-should-i-marshalas-for-character-type-in-fortran

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!