我正在从C#程序调用Fortran DLL。我设法传递一个Fortran派生类型作为参数,但是当调用一个返回派生类型作为返回值的函数时,我得到一个NullPointerException。
我怀疑我在C#端DLLImport中做错了什么。
Fortran图书馆:
module FortranCallBack
USE ISO_C_BINDING
IMPLICIT NONE
TYPE, BIND(C) :: FOO
INTEGER :: A, B
END TYPE
CONTAINS
SUBROUTINE Test(myFoo) BIND(C)
!DEC$ ATTRIBUTES DLLEXPORT :: Test
TYPE(FOO), INTENT(IN) :: myFoo
write (*,*) "Foo: ", myFoo%A, " ", myFoo%B
END SUBROUTINE
FUNCTION FuncTest() BIND(C) RESULT(RES)
!DEC$ ATTRIBUTES DLLEXPORT :: FuncTest
TYPE(FOO) :: RES
RES = FOO(42, 13)
END FUNCTION
和C#代码调用它:
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
[StructLayout(LayoutKind.Sequential)]
public class FOO
{
public int a;
public int b;
}
class Program {
static void Main(string[] args)
{
var f = new FOO { a = 1, b = 2 };
// This works
Test(f);
// Here I get NullPointerException...
FOO myFoo = FuncTest();
}
[DllImport("fortran_lib.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl, EntryPoint = "test")]
public static extern void Test( [In] FOO foo );
[DllImport("fortran_lib.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl, EntryPoint = "functest")]
public static extern FOO FuncTest();
}
}
代码使用英特尔Fortran 10.1和.NET framework 4.0进行编译