簡體   English   中英

將數組指針從Fortran(被調用方)傳遞到C#(調用方)

[英]Passing an array pointer from Fortran (callee) to C# (caller)

我試圖將一個浮點數組從C#傳遞給fortran,並讓fortran將其引用更改為內部(在fortran代碼中)數組。 我這樣做只是在獲得垃圾,盡管它運行良好。 以下是我的工作:

float[] test = new float[50];
testpointer_( test);

[DllImport("ArrayPointerTest.dll", CallingConvention = CallingConvention.Cdecl)]
static extern void testpointer_([Out] float[] array);//Out keyword makes no difference



!DEC$ ATTRIBUTES DLLEXPORT::testpointer
subroutine testpointer(arrayout)
  implicit none
real, dimension(1:50), target :: arrayin
real, dimension(:), pointer :: arrayout
integer :: i


DO i=1,50
    arrayin(i)=i
end do
arrayout => arrayin
end subroutine

為什么? 因為我正在將遺留代碼轉換為dll,並且不想進行任何不必要的更改。 有任何想法嗎?

使用接受的答案以及一些更改進行更新
這段代碼使C#:“ test”的目標值是fortran:“ arrayin”的值。

[DllImport("ArrayPointerTest.dll", CallingConvention = CallingConvention.Cdecl)]
        static unsafe extern void testpointer(float* arrayPtr);

  private unsafe static void PointerTest()
        {
            float[] teste = new float[50];
            teste[49] = 100;

            fixed (float* testePtr = teste)
            {
                testpointer(testePtr);
            }
            for (int i = 0; i < 50; i++)
            {
                Console.WriteLine(teste[i]);
            }
            Console.Read();
        }


!DEC$ ATTRIBUTES DLLEXPORT::testpointer
subroutine testpointer(arrayout_) bind(c)
  use iso_c_binding
  implicit none



real(c_float), dimension(1:50), target :: arrayin
type(c_ptr), value ::arrayout_
real(c_float), dimension(:), pointer :: arrayout

integer :: i

call c_f_pointer(arrayout_, arrayout, [50])

do i=1,50
        arrayin(i) = i*2!you can also change arrayout here, it will be reflected
end do

arrayout = arrayin ! todo: is this causing a copy to be made, or is it changing the pointer's references?


end subroutine

使用iso_c_binding

!DEC$ ATTRIBUTES DLLEXPORT::testpointer
subroutine testpointer(arrayout) bind(c)
  use iso_c_binding
  implicit none

real(c_float), dimension(1:50), target :: arrayin
real(c_float), dimension(:), pointer :: arrayout
integer :: i


DO i=1,50
    arrayin(i)=i
end do
arrayout => arrayin
end subroutine

使用bind(c)您也不需要修改過程名稱:

static extern void testpointer([Out] float[] array);//Out keyword makes no difference

您還必須注意傳遞數組。 我會使用c_ptr

!DEC$ ATTRIBUTES DLLEXPORT::testpointer
subroutine testpointer(arrayout_) bind(c)
  use iso_c_binding
  implicit none

type(c_ptr),value::arrayout_
real(c_float), dimension(:), pointer :: arrayout

call c_f_pointer(arrayout_, arrayout, [50])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM