Code archives/Miscellaneous/Cross-platform Dynamic Libraries

This code has been declared by its author to be Public Domain code.

Download source code

Cross-platform Dynamic Libraries by JoshK2013
This class will allow you to load dynamic libraries on all platforms. Specify the file name to load and the code will load either a ,dll or .so file by that name. You can then use GetFunction() to retrieve function pointers from the library and start using them.
SuperStrict

Import brl.filesystem
?win32
Import pub.win32
?
?Not win32
Import "-ldl"
?

Private

Extern "c"
?win32
	Function LoadLibrary:Int(path$z)
	Function GetProcAddress:Byte Ptr(name$z)
	Function FreeLibrary(handle:Int)
?
?Not win32
	Function dlopen:Int(path$z,Mode:Int)
	Function dlsym:Byte Ptr(handle:Int,name$z)
	Function dlclose(handle:Int)
?
EndExtern

?Not win32
Const RTLD_LAZY:Int=1
?

Public

Type TLibrary
	
	Field handle:Int
	
	Method Delete()
		Free()
	EndMethod	
	
	Method Free()
		If handle
?win32
			FreeLibrary handle
?
?Not win32
			dlclose handle
?
			handle=0
		EndIf
	EndMethod
	
	Method GetFunction:Byte Ptr(name:String)
?win32
		Return GetProcAddress(handle,name)
?
?Not win32
		Return dlsym(handle,name)
?
	EndMethod
	
	Function Load:TLibrary(path:String)
		Local library:TLibrary=New TLibrary
		Select ExtractExt(path).ToLower()
		Case "dll","so"path=StripExt(path)
		EndSelect
		path=RealPath(path)
?win32	
		library.handle=LoadLibrary(path+".dll")
?
?Not win32
		library.handle=dlopen(path+".so",RTLD_LAZY)
?
		If Not library.handle Return Null
		Return library
	EndFunction
	
EndType

Comments

Brucey2013
By "on all platforms", you mean Linux and Windows only of course.


Derron2013
Are there other platforms? :D

Somehow I think: If Brucey writes such things, the handling within macs is differing way more than win<>linux.


bye
Ron


Code Archives Forum