C # local call of FORTRAN dynamic link library for mixed programming with FORTRAN

Source: Internet
Author: User
Document directory
  • 2. Compile a fortran program to generate a dynamic link library file

Preface

C # has developed into a very well-developed language. Based on the C language style, C ++ has evolved. And relies on the powerful. Net underlying framework. C # can be used to quickly build desktops and Web applications. However, in our actual work, although C # is already perfect, we still cannot complete all our work. In many engineering calculations, the computing speed, accuracy, and execution efficiency of C # language are not as high as those of the project. Therefore, we will consider whether there is a way to separate our engineering computing part from our project, and write the computing part in another language with faster execution and higher accuracy, then we call it in C # to complete our work. The answer is yes.

FORTRAN is an ancient language that is the world's first advanced programming language for computers and is widely used in science and engineering computing. With its unique functions, Fortran plays an important role in the field of numerical, scientific, and engineering computing. However, the FORTRAN program itself is not suitable for developing independent applications, such as traditional desktop applications or web applications. Therefore, we want to combine C # with Fortran. C # can use FORTRAN to implement programs with higher accuracy and faster computing, while Fortran can achieve visual design through C.

 

I. Basic Ideas

Use FORTRAN to compile a dynamic link library (DLL), provide the computing function interface in the DLL, and then call the computing function of the DLL in C # To implement the calculation process.

Note that, because we use the Fortran compiler, the generated DLL is a third-party Unmanaged DLL, so we cannot directly add DLL references to the program. The specific practices will be described later.

 

2. Compile a fortran program to generate a dynamic link library file

After knowing the idea, we will start the formal coding. Create an empty Fortran dynamic-Link Library Project.

In Intel (r) Visual Fortran, click library, select Dynamic-Link Library in the right figure, and click OK. The project is as follows:

Click the sources file folder and select the new item.

Add a new Fortran File

Then you can write the Fortran code. Here we mainly implement two methods:

One method is to calculate the sum of the two numbers and return the result.

The other is to input an array, sort the array, find the maximum value, return the sorting result, and return the maximum value.

Here we demonstrate the differences between a number and an array in FORTRAN.

The basic syntax of FORTRAN is not in the scope of this article. Please check your documents on your own.

The following shows the specific Fortran code for implementing the above functions:

DOUBLE PRECISION FUNCTION ADD(A,B)!DEC$ ATTRIBUTES DLLEXPORT::ADD!DEC$ ATTRIBUTES STDCALL,ALIAS:'Add'::ADD    DOUBLE PRECISION:: A,B    ADD=A+BENDFUNCTION SORTANDFINDMAX(ARRAY,LENGTH)!DEC$ ATTRIBUTES DLLEXPORT::SORTANDFINDMAX!DEC$ ATTRIBUTES STDCALL,ALIAS:'Sortandfindmax'::SORTANDFINDMAXDOUBLE PRECISION ::ARRAY(LENGTH)INTEGER::I,JDOUBLE PRECISION::SORTANDFINDMAX,TEMPSORTANDFINDMAX=ARRAY(1)DO I=1,LENGTH-1    DO J=I+1,LENGTH        IF(ARRAY(I).GT.ARRAY(J)) THEN            TEMP=ARRAY(I)            ARRAY(I)=ARRAY(J)            ARRAY(J)=TEMP            SORTANDFINDMAX=ARRAY(J)            END IF    END DO    END DOEND

The preceding two Fortran functions are declared. One is to calculate the sum of two numbers, and the other is to select sorting and find the maximum value.

Then, click build solution of Visual Studio to compile it into a DLL.

Description of the code segment:

! Dec $ attributes dllexport: add

! Dec $ attributes stdcall, alias: 'add': add

These two statements are critical. The following three similarities are used to briefly describe the meaning of the above code snippet and the problems that need to be paid attention to when calling C.

1. function names are consistent:

In the Fortran compiler, all export function names are in uppercase by default. When calling Fortran DLL in C #, you must specify the same function name. In FORTRAN, the solution is to use the alias (alias) attribute to specify the export function name.

For example, for the following Fortran functions:

DOUBLE PRECISION FUNCTION ADD(A, B)!DEC$ ATTRIBUTES DLLEXPORT:: ADDDOUBLE PRECISION A,B  ADD =A+BEND

The corresponding C # statement is:

[DllImport("MathDll")]private static extern double ADD (double A, double B);

The modified alias is defined as follows:

Double Precision Function ADD (A, B)!DEC$ ATTRIBUTES DLLEXPORT:: ADD!DEC$ ATTRIBUTES ALIAS:'Add' :: AddDouble Precision A,B  Add =A+BEnd

The corresponding C # statement is:

[DllImport("MathDll")]private static extern double Add (double A, double B);

The solution provided in C # is to specify the exported Fortran function name by using the entrypoint attribute of dlllmport.

For example:

Double Precision Function ADD(A, B)!DEC$ ATTRIBUTES DLLEXPORT:: ADDDOUBLE PRECISION A,B  ADD =A+BEND

The corresponding C # statement is:

[DllImport("MathDll",EntryPoint = " ADD ")]private static extern double Plus(double A, double B);

You can also use the dumpbin.exe tool of. Net framework.exe to view the name of the function exported by DLL.

A. Open the Microsoft Visual Studio 2010/Visual Studio Tools/Visual Studio 2010 command prompt in the Start Menu.

B. In the command prompt, point the path to the path for compiling the. dll file, and enter the following command:

Dumpbin/exports filename. dll

You can view all function information exported from filename. Dil in the current directory.

2. Consistent stack Management

Stack management conventions include: number and sequence of parameters accepted by the subroutine during the call process, and which party clears the stack after the call is completed. C # The default call mode of C # language on Windows is stdcall, which is used by the caller to clear the stack. By default, the Fortran language is cleared by the caller. Therefore, you must call the stack clearing methods of both parties to ensure normal function calls between the two languages. This convention can be unified in FORTRAN or C # languages.

In FORTRAN, You can compile the command "! The optional "C" or "stdcall" parameter after Dec $ "is implemented:

A.

!DEC$ ATTRIBUTES STDCALL ::Object

The stdcall mode in this statement specifies that the stack is cleared by the called party (where "object" is the variable name or function name ).

B.

!DEC$ ATTRIBUTES C :: Object

The C-mode declaration in this statement is cleared by the main call function (but this method cannot be used when passing array and string parameters ).

If you make changes in the C # language, you need to set the value of the callingconvention field in the dllimport attribute to cdecl (indicating that the caller clears the stack) or stdcall (indicating that the stack is cleared by the called party ).

[DllImport("FileName.dll", CallingConvention = CallingConvention.StdCall)][DllImport("FileName.dll", CallingConvention = CallingConvention.Cdecl)]

Normal calling can be ensured only when the stack management of the Fortran Program and the C # program is consistent.

3. Consistent parameter types

Common Data parameter types in FORTRAN include:

Real: Indicates the floating point data type, that is, decimal places. It is equivalent to the float of C,

Integer: Indicates the integer type, which is equivalent to the int data type of C #.

Double Precision: Double data type, which is equivalent to the double data type of C.

When calling Fortran DLL in C #, the parameter consistency must be ensured. For example, if the variable in FORTRAN defines the real type and the input is a double type, a computing error occurs.

3. compile C # code to call Fortran DLL

 

C # The process of calling FORTRAN is very simple. You only need to pay attention to the above issues.

 

Here we will first create a new console application:

 

 

Copy the DLL generated by the compiled Fortran project to the debug folder of the console application.

Next we add a class: fortranmethod. CS

This class is used to call Fortran DLL.

The Code is as follows:

using System;using System.Text;using System.Runtime.InteropServices;namespace MixedProgram{   public static class FortranMethod    {       [DllImport("TestDll.dll",CallingConvention = CallingConvention.Cdecl)]       public static extern double Add(double a, double b);       [DllImport("TestDll.dll", CallingConvention = CallingConvention.Cdecl)]       public static extern double Sortandfindmax(double[] array, int length);    }}

Precautions for Calling C # are described above and will not be discussed here.

Then test our Fortran DLL in the main function.

The sample code is as follows:

Using system; using system. collections. generic; using system. text; namespace mixedprogram {class program {static void main (string [] ARGs) {console. writeline ("enter two numbers and add them together:"); double num1 = convert. todouble (console. readline (); double num2 = convert. todouble (console. readline (); console. writeline ("the two numbers entered are:" + num1 + "," + num2); double sum = fortranmethod. add (num1, num2); console. writeline ("sum result:" + sum); double [] array = {, 6}; console. writeline ("Initial array:"); For (INT I = 0; I <array. length; I ++) console. write (array [I] + ""); Double B = fortranmethod. sortandfindmax (array, array. length); console. writeline ("\ n" + "sorted:"); For (INT I = 0; I <array. length; I ++) console. write (array [I] + ""); console. writeline ("\ n" + "maximum value:"); console. writeline (B); console. readkey ();}}}

So far, the work has been completed. Let's take a look at the results below:

So far, the small examples of C # and FORTRAN programming have been completed.

 

 

Summary:

 

This article mainly demonstrates how to use C # To call the Fortran DLL for related computing. This section mainly describes precautions for Calling C. In engineering computing, if the accuracy requirement is high and the calculation is complicated, we can consider using the hybrid programming of C # and FORTRAN to meet the required requirements. This article is based on local call of fortran dll. The next article will explain how to call Fortran DLL based on Web.

 

About C # and FORTRAN mixed programming can also participate in this article: http://www.iepi.com.cn/BBS_CN/forum.php? MoD = viewthread & tid = 62 & extra = Page % 3d1

 

 

(All Rights Reserved. For details, refer to the source)

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.