Return a character string from a C function in a shared library (Dyalog APL)

76 Views Asked by At

I need to call a C function that returns a character string. The function is in a shared library (Linux)

I have written this simple test function in C.

wchar_t *retc(wchar_t *in) {
    FILE *fp = fopen("debug.log", "w");  //open a file for logging the result string
    static wchar_t string[128];
    swprintf(string, 128, L"ciao ciao %ls", in);
    fprintf(fp, "%ls", string);
    fclose(fp);
    return string;
}

In Dyalog APL I code:

 ⎕na 'T libdebug.so|retc <0T'
 retc ⊂'Bye Bye'  ⍝ can I get a readable result?
������
$ cat debug.log
ciao ciao Bye Bye 

What would be the proper way to obtain a string as a return value from a C function?

1

There are 1 best solutions below

2
LdBeth On

Whenever need to pass an array (or many arrays) from C back to Dyalog APL (or J, the difference is J exposes runtime objects directly writable by C but Dyalog does not) runtime, it is good practice use output parameter so APL can allocate and manage the space for the returned arrays, instead of just return a pointer from C, because either if it uses static allocated memory it is not thread safe, or if it is dynamic allocated the APL runtime won't able to free them. Only use a return type specifier when the return result is something passed as a value in C.

#include <stdio.h>
#include <wchar.h>

void test(wchar_t *in, wchar_t *out){
  // in reality it is a good idea to pass size
  // allocated for output to C
  swprintf(out, 128, L"A wide string: %ls", in);
}
      ⎕NA 'libtest.dylib|test <0T >0T'
      test 'Hello!' 128 ⍝ Specify the size allocated for return string.
A wide string: Hello!

Your example is wrong in the way that it makes Dyalog APL try to interpret the returned pointer as a wide char value, which gives garbage value.

Check Dyalog APL Language Reference Guide.pdf shipped with your local installation or get it from Dyalog.com website. It has about 30-ish pages description on how to use ⎕NA and some pretty advanced usages are covered.