C and non-C methods without code duplication

Share your advanced PureBasic knowledge/code with the community.
User avatar
eddy
Addict
Addict
Posts: 1479
Joined: Mon May 26, 2003 3:07 pm
Location: Nantes

C and non-C methods without code duplication

Post by eddy »

I recently I've faced this following problem : how to manage cross-platform code without code duplication.

Here is the original code :

Code: Select all

CompilerIf #PB_Compiler_OS=#PB_OS_Linux  
   Import ""
CompilerElse
   ImportC ""
CompilerEndIf

   GenerateGUID(*guid.GUID)
EndImport

CompilerIf #PB_Compiler_OS=#PB_OS_Linux
   Prototype.s GetRandomKey(*guid.GUID, passCount, mode$)
CompilerElse
   PrototypeC.s GetRandomKey(*guid.GUID, passCount, mode$)
CompilerEndIf
Structure API
      GetRandomKey.GetRandomKey
EndStructure

CompilerIf #PB_Compiler_OS=#PB_OS_Linux
   Procedure.s GetRandomKey(*guid.GUID, passCount, mode$)
CompilerElse
   ProcedureC.s GetRandomKey(*guid.GUID, passCount, mode$)
CompilerEndIf
   ;CODE HERE....
EndProcedure

API.API
API\GetRandomKey=@GetRandomKey()
:arrow: optimized solution :

Code: Select all

CompilerIf #PB_Compiler_OS=#PB_OS_Linux ;<=== your custom condition here
   Macro _C(p) : p : EndMacro
CompilerElse
   Macro _C(p) : p#C : EndMacro
CompilerEndIf

; ******************************
; EXAMPLE
; ******************************
_C(Import) ""
   GenerateGUID(*guid.GUID)
EndImport

_C(Prototype).s GetRandomKey(*guid.GUID, passCount, mode$)
Structure API
   GetRandomKey.GetRandomKey
EndStructure

_C(Procedure) GetRandomKey(*guid.GUID, passCount, mode$)
   ;CODE HERE....
EndProcedure

API.API
API\GetRandomKey=@GetRandomKey()
Imagewin10 x64 5.72 | IDE | PB plugin | Tools | Sprite | JSON | visual tool