Store and Load the SUB's from file possible?

General FreeBASIC programming questions.
Post Reply
mrminecrafttnt
Posts: 131
Joined: Feb 11, 2013 12:23

Store and Load the SUB's from file possible?

Post by mrminecrafttnt »

Ive tried to do this and got an Syntax Error.. xD

Code: Select all

'Step1 Create Code
sub test
    print "Hello World"
end sub

'Step2 Write Code to binary
open "code.bin" for binary as #1
put #1,,test
close #1

'Step3 Load and execute code
dim as sub code
open "code.bin" for binary as #1
get #1,,code
close #1
code()
dodicat
Posts: 7983
Joined: Jan 10, 2006 20:30
Location: Scotland

Re: Store and Load the SUB's from file possible?

Post by dodicat »

Only within the life of your code, you could use a pointer.
run first with createfile.
then comment out createfile and run (to test outside your code)

Code: Select all

'Step1 Create Code
sub test
    print "Hello World"
end sub

'Step2 Write Code to binary

#macro createfile
open "code.bin" for binary as #1
dim as any ptr p=@test
put #1,,cint(p)
close #1
#endmacro


createfile

'Step3 Load and execute code
dim as integer code
open "code.bin" for binary as #1
get #1,,code
close #1
cast(sub,code)()
sleep
 
Not using createfile is the same as calling the pointer from another code, it seems to work here, but it is probably not guaranteed to work.
caseih
Posts: 2157
Joined: Feb 26, 2007 5:32

Re: Store and Load the SUB's from file possible?

Post by caseih »

mrminecrafttnt wrote: Mar 16, 2023 10:02Ive tried to do this and got an Syntax Error.. xD
Simply dumping and loading into memory won't work because in-memory code has been modified by the loader and linker to only work in that specific location of memory, with the specific memory layout of the running program at that time. Also some operating systems restrict where executable code can be in the address space and general heap allocations often are not executable.

What you want to do can only be accomplished with dynamically-linked libraries (DLLs), which can be loaded at run time and have the linker fix up all the memory references to point at the correct things. Well technically you could build your own loader and linker I suppose. OS-level stuff. What you're looking for is https://www.freebasic.net/wiki/KeyPgDylibload.
Post Reply