Objective
C # has evolved into a fairly sophisticated language, based on the C-language style, which evolved in C + +. And rely on the powerful. NET underlying framework. C # can be used to quickly build desktop and Web applications. However, in our actual work, although C # has been very well-developed, it is still unable to complete all of our work. In many engineering calculations, the computational speed, precision, and execution efficiency of the C # language are relatively less than the requirements of the project. So we'll consider whether there's a way to separate our engineering calculations from our projects, write the compute parts in another language that executes faster and more precise, and then call in C # and finish our work. The answer is yes.
Fortran is an ancient language, it is the world's first high-level computer programming language, widely used in the field of science and engineering computing. Fortran language plays an important role in the field of numerical, scientific and engineering computing with its unique functions. However, the FORTRAN program itself is not suitable for developing standalone applications, such as our traditional desktop applications or Web applications. So here we want to combine C # with Fortran, C # with FORTRAN to achieve higher precision, faster computing programs, and Fortran through C #, you can also achieve visual design.
first, the basic idea
Using Fortran, write a dynamic-link library (DLL), provide a computed function interface in a DLL, and then call the function in C # to compute part of the DLL to implement the computational process.
It is important to note that since we are using a FORTRAN compiler, the resulting DLL belongs to a third-party unmanaged DLL, so you cannot add a DLL reference directly to the program. Specific practices will be described in the following sections.
Second, write Fortran program, generate dynamic link library file
After knowing the train of thought, we begin the formal coding. Start by creating an empty Fortran Dynamic-link library project.
In Intel (R) Visual Fortran Click Library, select the Dynamic-link library on the right. then click OK. The project is as follows:
Click the Sources file folder and select New Item.
Add a new Fortran file
The Fortran code is then written. Here we mainly implement two methods:
One method is to ask for a sum of two numbers and return the result.
The other is to enter an array, sort the array, find the maximum value, return the sorted result, and return the maximum value.
Here we are demonstrating the difference between a number in Fortran and an array.
The basic syntax of FORTRAN is not the scope of this article, please read the information on your own.
The specific FORTRAN code for the functionality we want to implement is given below:
1 DOUBLE PRECISION FUNCTION ADD (A, b)2!dec$ ATTRIBUTES Dllexport::add3! dec$ ATTRIBUTES Stdcall,alias:'ADD':: ADD4 DOUBLE PRECISION:: A, B5add=a+B6 END7 8 FUNCTION Sortandfindmax (array,length)9!dec$ ATTRIBUTES Dllexport::sortandfindmaxTen! dec$ ATTRIBUTES Stdcall,alias:'Sortandfindmax':: Sortandfindmax One DOUBLE PRECISION:: ARRAY (LENGTH) A integer::i,j - DOUBLE precision::sortandfindmax,temp -Sortandfindmax=array (1) theDo 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) A END IF at END Do - END Do -END
Above we have declared two FORTRAN functions, one is to calculate the sum of two numbers, one is to select the sort and find the maximum value.
We then clicked Visual Studio Build solution. Start compiling into a DLL.
About Code Snippet Interpretation:
! dec$ ATTRIBUTES Dllexport::add
! dec$ ATTRIBUTES stdcall,alias: ' Add ':: Add
These two lines of code are critical. The following three consistent to simply say the above code snippet meaning and C # calls need to pay attention to the problem.
1. Function names are the same:
The default export function names in the FORTRAN compiler are all uppercase. While invoking a Fortran DLL in C #, you must specify a function name that is consistent. A FORTRAN solution is to use the alias attribute to specify the name of the exported function.
For example, the following Fortran function:
1 DOUBLE PRECISION FUNCTION ADD (A, B) 2 3 ! dec$ ATTRIBUTES DLLEXPORT:: ADD 4 5 DOUBLE PRECISION A , b 6 7 ADD =a+B89 END
The corresponding C # declaration is:
[DllImport ("mathdll")] Private Static extern Double ADD (doubledouble B);
Use alias to modify the following definition:
1 Double Precision Function ADD (A, B) 2 3 ! dec$ ATTRIBUTES DLLEXPORT:: ADD 4 5 ! dec$ ATTRIBUTES ALIAS:'add' :: Add 6 7Double Precision A, a 8 9 Add =a+Bten End
The corresponding C # declaration is:
[DllImport ("mathdll")] Private Static extern Double ADD (doubledouble B);
The solution provided in C # is to specify the exported FORTRAN function name by using the EntryPoint property of Dlllmport.
For example:
1 Double Precision Function ADD (A, B) 2 3 ! dec$ ATTRIBUTES DLLEXPORT:: ADD 4 5 DOUBLE PRECISION A , b 6 7 ADD =a+B89 END
The corresponding C # declaration is:
[DllImport ("mathdll""")] Private Static extern Double Plus (doubledouble B);
In addition, you can use the Dumpbin.exe tool provided with the. NET framework to view the function names exported by the 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 form, point to the path to the compiled build. dll file, and then enter the following command:
Dumpbin/exports FileName.dll
You can view all the function information exported in Filename.dil under the current directory.
2. Stack management consistent
The stack management conventions include: the number and order of parameters that are accepted by the subroutine in the call procedure, which party cleans up the stack after the call is completed, and so on. The C # language invocation mode on the Windows platform defaults to stdcall mode, which is cleaned up by the callee. The Fortran language is cleared by the caller by default. Therefore, it is necessary to uniformly call the two sides of the stack cleanup to guarantee the normal function calls between the 2 languages. This agreement can be used in FORTRAN or C # language to take measures to unify.
In Fortran language you can compile the instructions "! dec$ "The optional" C "or" stdcall "parameter to:
A.
! dec$ ATTRIBUTES stdcall:: Object
The stdcall pattern in the statement statement specifies that the stack is purged by the callee (where "Object" is the variable name or function name).
B.
! dec$ ATTRIBUTES C:: Object
The C-mode declaration in the statement clears the stack by the key function (but cannot be specified with this method when passing array and string arguments).
If you make changes within the C # language, you need to set the value of the CallingConvention field in the DllImport property to cdecl (which means that the stack is cleaned up by the caller) or stdcall (which means that the stack is cleaned up by the callee).
[DllImport ("FileName.dll", callingconvention = callingconvention.stdcall)] [ DllImport ("FileName.dll", callingconvention = callingconvention.cdecl)]
Normal invocation is guaranteed only if the FORTRAN program is consistent with the stack management of the C # program.
3. Parameter types remain consistent
The types of data parameters commonly used in FORTRAN are:
REAL: Represents a floating-point data type, which is a decimal, equivalent to float in C #,
integer: Represents an integral type, equivalent to the INT data type of C #
DOUBLE PRECISION: Represents a double data type, which is equivalent to the double data type of C #.
In C # calling a Fortran DLL is necessary to ensure consistency of parameters, for example, in Fortran, the variable is defined by the real type, and we pass in a double, then there will be a calculation error.
Third, write C # code call FORTRAN DLL
C # calls to the FORTRAN process is very simple, only need to pay attention to the above mentioned several problems can be.
Here we start by creating a new console application:
Then copy the DLLs generated by our compiled FORTRAN project to the Debug folder of the console application.
Next we add a class: FortranMethod.cs
This class is used to invoke a Fortran DLL.
The code is as follows:
1 usingSystem;2 usingSystem.Text;3 usingSystem.Runtime.InteropServices;4 5 namespaceMixedprogram6 {7 Public Static classFortranmethod8 {9[DllImport ("TestDll.dll", CallingConvention =callingconvention.cdecl)]Ten Public Static extern DoubleADD (DoubleADoubleb); One A[DllImport ("TestDll.dll", CallingConvention =callingconvention.cdecl)] - Public Static extern DoubleSortandfindmax (Double[] Array,intlength); - } the}
The considerations for C # Invocation are described above and are no longer discussed here.
Then test our Fortran DLL in the main function.
The sample code is as follows:
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Text;4 5 namespaceMixedprogram6 {7 class Program8 {9 Static voidMain (string[] args)Ten { OneConsole.WriteLine ("Please enter two numbers to add:"); A Doublenum1=convert.todouble (Console.ReadLine ()); - - Doublenum2 =convert.todouble (Console.ReadLine ()); theConsole.WriteLine ("the two numbers entered are:"+ NUM1 +" ,"+num2); - Doublesum =Fortranmethod.add (num1,num2); -Console.WriteLine ("The sum result is:"+sum); - + Double[] Array = {1,5,2,4,3,7,6}; -Console.WriteLine ("Initial array:"); + for(inti =0; i < Array.Length; i++) AConsole.Write (array[i]+" "); at - Doubleb=Fortranmethod.sortandfindmax (Array, array.length); -Console.WriteLine ("\ n"+"after sorting:"); - - for(inti =0; i < Array.Length; i++) -Console.Write (array[i]+" "); in -Console.WriteLine ("\ n"+"The maximum value is:"); to Console.WriteLine (b); + - Console.readkey (); the } * } $}
So far, so the work is done, here's a look at the results:
So far, a small example of C # and FORTRAN programming has been completed.
Summarize:
This article demonstrates how to use C # to invoke a Fortran DLL to implement the relevant calculations. and mainly on the C # call should pay attention to matters. In engineering calculations, if the accuracy requirement is high and the calculation is more complex, we can consider the mixed programming with C # and Fortran to achieve the required requirements. This article is based on a local call to the Fortran DLL, and the next article will explain the Web-based call to the FORTRAN DLL.
About C # and Fortran hybrid programming you can also join this article: http://www.iepi.com.cn/BBS_CN/forum.php?mod=viewthread&tid=62&extra=page%3D1
This article transferred from: http://www.cnblogs.com/potential/archive/2012/11/05/2755899.html
[Reprint:] C # and Fortran mixed programming local call FORTRAN dynamic link library