假设我有以下 Fortran 代码
subroutine COMPLEX_PASSING(r, i, c)
!DEC$ ATTRIBUTES DLLEXPORT::COMPLEX_PASSING
REAL*8 :: r, i
COMPLEX*8 :: c
c = cmplx((r * 2), (i * 2))
return
end
Fortran 代码是用
gfortran -c complex_passing.f90
gfortran -fPIC -shared -o complex_passing.dll complex_passing.o
我将如何在 C# 中调用此子例程?我尝试了以下代码:
using System;
using System.Runtime.InteropServices;
namespace FortranCalling {
class Program {
static void main(string[] args) {
double real = 4;
double imaginary = 10;
COMPLEX c = new COMPLEX();
complex_passing( ref real, ref imaginary, ref c);
Console.WriteLine("Real: {0}\nImaginary: {1}", c.real, c.imaginary);
Console.ReadLine();
}
[StructLayout(LayoutKind.Sequential)]
struct COMPLEX {
public double real;
public double imaginary;
}
[DllImport("complex_passing.dll", EntryPoint = "complex_passing_", CallingConvention = CallingConvention.Cdecl)]
static extern void complex_passing(ref double r, ref double i, ref COMPLEX c);
}
}
收效甚微 - 我的 COMPLEX 结构似乎正在返回垃圾数据:
Real: 134217760.5
Imaginary: 0
当我期望实部是 8 而虚部是 20 时。