Skip to content

Instantly share code, notes, and snippets.

@pwl
Created August 13, 2012 13:09

Revisions

  1. @invalid-email-address Anonymous created this gist Aug 13, 2012.
    8 changes: 8 additions & 0 deletions Makefile
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,8 @@
    default: script_embed
    ./script_embed

    script_embed: script_embed.f90 script_data.o
    gfortran -o $@ $^

    script_data.o: script_data.s script.lua
    gcc -c -o $@ $<
    2 changes: 2 additions & 0 deletions script.lua
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,2 @@
    -- This is an embedded Lua script.
    a = {1,2,3,4}
    4 changes: 4 additions & 0 deletions script_data.s
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,4 @@
    .section .rodata
    .global script
    script:
    .incbin "script.lua"
    68 changes: 68 additions & 0 deletions script_embed.f90
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,68 @@
    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 :: 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