December 04, 2020, 10:24:41 AM

Author Topic: [bmx] Cross-platform Dynamic Libraries by JoshK [ 1+ years ago ]  (Read 491 times)

Offline BlitzBot

  • Jr. Member
  • **
  • Posts: 1
Title : Cross-platform Dynamic Libraries
Author : JoshK
Posted : 1+ years ago

Description : 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.

Code :
Code: BlitzMax
  1. SuperStrict
  2.  
  3. Import brl.filesystem
  4. ?win32
  5. Import pub.win32
  6. ?
  7. ?Not win32
  8. Import "-ldl"
  9. ?
  10.  
  11. Private
  12.  
  13. Extern "c"
  14. ?win32
  15.         Function LoadLibrary:Int(path$z)
  16.         Function GetProcAddress:Byte Ptr(name$z)
  17.         Function FreeLibrary(handle:Int)
  18. ?
  19. ?Not win32
  20.         Function dlopen:Int(path$z,Mode:Int)
  21.         Function dlsym:Byte Ptr(handle:Int,name$z)
  22.         Function dlclose(handle:Int)
  23. ?
  24. EndExtern
  25.  
  26. ?Not win32
  27. Const RTLD_LAZY:Int=1
  28. ?
  29.  
  30. Public
  31.  
  32. Type TLibrary
  33.        
  34.         Field handle:Int
  35.        
  36.         Method Delete()
  37.                 Free()
  38.         EndMethod      
  39.        
  40.         Method Free()
  41.                 If handle
  42. ?win32
  43.                         FreeLibrary handle
  44. ?
  45. ?Not win32
  46.                         dlclose handle
  47. ?
  48.                         handle=0
  49.                 EndIf
  50.         EndMethod
  51.        
  52.         Method GetFunction:Byte Ptr(name:String)
  53. ?win32
  54.                 Return GetProcAddress(handle,name)
  55. ?
  56. ?Not win32
  57.                 Return dlsym(handle,name)
  58. ?
  59.         EndMethod
  60.        
  61.         Function Load:TLibrary(path:String)
  62.                 Local library:TLibrary=New TLibrary
  63.                 Select ExtractExt(path).ToLower()
  64.                 Case "dll","so"path=StripExt(path)
  65.                 EndSelect
  66.                 path=RealPath(path)
  67. ?win32 
  68.                 library.handle=LoadLibrary(path+".dll")
  69. ?
  70. ?Not win32
  71.                 library.handle=dlopen(path+".so",RTLD_LAZY)
  72. ?
  73.                 If Not library.handle Return Null
  74.                 Return library
  75.         EndFunction
  76.        
  77. EndType


Comments :


Brucey(Posted 1+ years ago)

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


Derron(Posted 1+ years ago)

 Are there other platforms? :DSomehow I think: If Brucey writes such things, the handling within macs is differing way more than win<>linux.byeRon


 

SimplePortal 2.3.6 © 2008-2014, SimplePortal