繁体   English   中英

在C#中使用模块变量同时在Fortran dll中调用方法

[英]Simultaneous calls of a method in a fortran dll with module variables, in C#

我试图同时在不同的线程中调用Fortran方法。 执行完全彼此独立并且与主线程完全独​​立。 问题在于,使用模块变量意味着该变量由dll全局设置,这意味着这两个调用将使用它,从而使程序没有崩溃,并因此发生。 这是我根据BálintAradi的回答所作的解释

C#

    static void Main(string[] args)
    {
        RunTwiceSync();//WORKS
        RunTwiceAsync();//INSTACRASH
    }

    private static void RunTwiceSync()
    {
        TestMyArray();
        TestMyArray();
    }

    private static void RunTwiceAsync()
    {
        ThreadStart ts = new ThreadStart(() =>
        {
            TestMyArray();
        });
        Thread t = new Thread(ts);
        t.Start();
        TestMyArray();
    }

    private static void TestMyArray()
    {
        Console.WriteLine("START");
        int size = 52;
        float[] myarray = new float[size];
        sub_(ref size, myarray);
        Console.WriteLine(myarray.Select(x => x.ToString()).Aggregate((x, y) => x + ";" + y));
        Console.ReadLine();
    }


    [DllImport("FortranArraySimpleTest.dll", CallingConvention = CallingConvention.Cdecl)]
    static extern void sub_(ref int size, float[] myarray);

福特兰

 !DEC$ ATTRIBUTES DLLEXPORT::ingammaextern
subroutine sub(size, myarray)
    use module1   ! * REMOVING MODULE USAGE FIXES THE PROBLEM
  implicit none
INTEGER  :: size
integer :: assignme
REAL, dimension(1:size) :: myarray

assignme = size
allocate(alocarray(1:assignme))
deallocate(alocarray)
end subroutine
! ************************************begin another file***********
      MODULE module1
      IMPLICIT NONE


real, dimension(:), allocatable :: alocarray
      END MODULE module1

这个解决方案,即删除模块,非常麻烦,而且维护起来很麻烦,因为代码使我提出的问题很大。

环境: GNU Fortran编译器,Windows 7 64位,fortran的CodeBlocks,VS2012,我没有更改任何编译器选项。

有任何想法吗?

感谢您的时间

可以做的是将模块更改为派生类型,然后随每次调用传递

module orig
  use whatever

  interfaces

  small types

  variables

contains

  procedures

end module

module state_class

  use whatever

  interfaces

  small types

  shared variables

  type state
    non shared variables
  contains
    procedure :: the procedures
    (not obligatory)
  end type

contains

  procedures changed to accept one additional argument:
  a passed dummy argument class(state)
  or just a regular dummy argument type(state)

end module

每个线程都有自己的state类实例,并显式地传递它或作为传递的伪参数传递它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM