Skip to content

Instantly share code, notes, and snippets.

@pwl
Created August 13, 2012 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pwl/3340727 to your computer and use it in GitHub Desktop.
Save pwl/3340727 to your computer and use it in GitHub Desktop.
Lua script embedding in fortran
default: script_embed
./script_embed
script_embed: script_embed.f90 script_data.o
$(FC) -o $@ $^
script_data.o: script_data.s script.lua
gcc -c -o $@ $<
clean:
rm -f script_embed script_data{.o} data.mod iso_c_utilities.mod
-- This is an embedded Lua script.
a = {1,2,3,4}
.section .rodata
.global script
script:
.incbin "script.lua"
.int 0
module iso_c_utilities
use iso_c_binding ! intrinsic module
interface
pure function strlen(string) result(len) bind(c,name="strlen")
use iso_c_binding
type(c_ptr), value, intent(in) :: string ! a c pointer
integer(c_int) :: len
end function strlen
end interface
contains
function c_f_string(cptr) result(str)
type(c_ptr), intent(in) :: cptr ! the c address
character(len=:), allocatable :: str
integer :: i
character(kind=c_char), dimension(:), pointer :: fptr
allocate(character(len=strlen(cptr)) :: str)
if(c_associated(cptr)) then
call c_f_pointer(fptr=fptr, cptr=cptr, shape=[strlen(cptr)])
do i = 1, strlen(cptr)
str(i:i) = fptr(i)
end do
end if
end function c_f_string
end module iso_c_utilities
module data
use iso_c_binding
use iso_c_utilities
private
character(c_char), target :: c_str
bind(C, name="script") :: c_str
public get_text
contains
function get_text()
character(len=:), allocatable :: get_text
get_text = c_f_string(c_loc(c_str))
end function get_text
end module data
program text
use data
use iso_c_binding
use iso_c_utilities
character(len=:), allocatable :: str
str = get_text()
print *, "[["
print *, str
print *, "]]"
print *, len(str)
end program text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment