In this example no Lisp string is needed when calling. The :reference-return type converts a foreign string of lowercase ASCII characters to a Lisp string on return. Here is the C code for the example.
#include <string.h>
#include <stdlib.h>
__declspec(dllexport) void __cdecl random_string(int length, char *string)
{
int ii;
for (ii = 0; ii < length ; ii++)
string[ii] = 97 + rand() % 26;
string[length] = 0;
}
#include <string.h>
#include <stdlib.h>
void random_string(int length, char *string)
{
int ii;
for (ii = 0; ii < length ; ii++)
string[ii] = 97 + rand() % 26;
string[length] = 0;
}
In this foreign function definition the :reference-return type must specify a size, since memory is allocated for it before calling the C function. Note also the use of
:lambda-list
so that the caller doesn't have to pass a dummy argument for the return-string, and
:result-type nil
correponding to the void declaration of the C function.
(fli:define-foreign-function (random-string
"random_string"
:source)
((length :int)
(return-string (:reference-return
(:ef-mb-string
:limit 256))))
:result-type nil
:lambda-list (length &aux return-string)
:calling-convention :cdecl)
(random-string 3)
=>
"uxw"
(random-string 6)
=>
"fnfozv"