Task

Show how a foreign language function can be called from the language.



As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap).



Notes

 It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.
 C++ and C solutions can take some other language to communicate with.
 It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative.


See also

   Use another language to call a function


' FB 1.05.0 Win64
 
'Using StrDup function in Shlwapi.dll
Dim As Any Ptr library = DyLibLoad("Shlwapi")
Dim strdup As Function (ByVal As Const ZString Ptr) As ZString Ptr
strdup = DyLibSymbol(library, "StrDupA")
 
'Using LocalFree function in kernel32.dll
Dim As Any Ptr library2 = DyLibLoad("kernel32")
Dim localfree As Function (ByVal As Any Ptr) As Any Ptr
localfree = DyLibSymbol(library2, "LocalFree")
 
Dim As ZString * 10 z = "duplicate"  '' 10 characters including final zero byte
Dim As Zstring Ptr pcz = strdup(@z)  '' pointer to the duplicate string
Print *pcz                           '' print duplicate string by dereferencing pointer 
localfree(pcz)                       '' free the memory which StrDup allocated internally 
pcz = 0                              '' set pointer to null                    
DyLibFree(library)                   '' unload first dll
DyLibFree(library2)                  '' unload second fll 
End