User defined subroutines with ANSI C

Numerical methods and mathematical models of Elmer
Post Reply
mb5
Posts: 20
Joined: 10 Jun 2017, 18:07
Antispam: Yes

User defined subroutines with ANSI C

Post by mb5 »

Hi,

for more complex functions I want to use the udf's instead of MATC. But I´ve never worked with FORTRAN before. Is there a possibility to use ANSI C for that task?

Best regards
Martin
mzenker
Posts: 1999
Joined: 07 Dec 2009, 11:49
Location: Germany

Re: User defined subroutines with ANSI C

Post by mzenker »

Hi,

not that I know of. But it is not that hard, you can have a look at the Solver Manual and the Programmer's Manual for some examples. Combined with one of the numerous FORTAN references on the web, you will get into it quickly.

HTH,

Matthias
Kitpaddel
Posts: 5
Joined: 26 May 2016, 01:10
Antispam: Yes

Re: User defined subroutines with ANSI C

Post by Kitpaddel »

Hi,

you can combine fortran and c. I once wrote a wrapper udf function that called a c function.

Wrapper something like this:

Code: Select all

FUNCTION udfcall(Model, n, var) RESULT(r)

USE DefUtils
use iso_c_binding

interface
function udfCallC (someConst, x, y, z, var) bind(c)
use DefUtils
use iso_c_binding
REAL(KIND=dp) :: udfCallC
INTEGER(KIND=dp), VALUE :: someConst
REAL(KIND=dp), VALUE :: x, y, z, var
end function udfCALLC
end interface

TYPE(Model_t) :: Model
INTEGER :: n
REAL(KIND=dp) :: var, r
REAL(KIND=dp) :: x, y, z
INTEGER(KIND=dp) :: someConst
LOGICAL :: Found
someConst = GetInteger(Model % Constants, "SomeConstant", Found)
IF(.NOT.Found) CALL Fatal("udfCall", "Unable to find SomeConstant")
x = Model % Nodes % x(n)
y = Model % Nodes % y(n)
z = Model % Nodes % z(n)
r = udfCallC(someConst, x,y,z,var)
END FUNCTION udfcall
And then a C method:

Code: Select all

extern "C"
{

double udfcallC(int someConst,
                double x,
                double y,
                double z,
                double var
                ) {

    
    return x+y+50; // Calculate your result here

}
}
You need to compile booth with the appropriate compiler into object files and link them into a single library file.

I don't know if it is possible to access the internal elmer data structures from the C method. So you might need to acquire all information you need in the fortran method and give them as arguments to the C method (as shown for the node coordinates and a model constant in this example).

Regards
mb5
Posts: 20
Joined: 10 Jun 2017, 18:07
Antispam: Yes

Re: User defined subroutines with ANSI C

Post by mb5 »

Thank you altogether. The second method seems very interesting for me. I don`t need the data structure for "Model_t" in my C-library. It should be possible for me to write a wrapper in Fortran ;)
I will test if a get FORTRAN and C together with the compiler/linker.

Best regards
Martin
Post Reply