How to resolve the algorithm Call a foreign-language function step by step in the Fortran programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Call a foreign-language function step by step in the Fortran programming language
Table of Contents
Problem Statement
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Call a foreign-language function step by step in the Fortran programming language
Source code in the fortran programming language
module c_api
use iso_c_binding
implicit none
interface
function strdup(ptr) bind(C)
import c_ptr
type(c_ptr), value :: ptr
type(c_ptr) :: strdup
end function
end interface
interface
subroutine free(ptr) bind(C)
import c_ptr
type(c_ptr), value :: ptr
end subroutine
end interface
interface
function puts(ptr) bind(C)
import c_ptr, c_int
type(c_ptr), value :: ptr
integer(c_int) :: puts
end function
end interface
end module
program c_example
use c_api
implicit none
character(20), target :: str = "Hello, World!" // c_null_char
type(c_ptr) :: ptr
integer(c_int) :: res
ptr = strdup(c_loc(str))
res = puts(c_loc(str))
res = puts(ptr)
print *, transfer(c_loc(str), 0_c_intptr_t), &
transfer(ptr, 0_c_intptr_t)
call free(ptr)
end program
You may also check:How to resolve the algorithm Events step by step in the Lingo programming language
You may also check:How to resolve the algorithm Strip whitespace from a string/Top and tail step by step in the Zoea programming language
You may also check:How to resolve the algorithm Yin and yang step by step in the D programming language
You may also check:How to resolve the algorithm Digital root step by step in the 11l programming language
You may also check:How to resolve the algorithm Sockets step by step in the Haskell programming language