Use another language to call a function: Difference between revisions

From Rosetta Code
Content added Content deleted
m (Category {{task|Programming environment operations}})
m (omit TI-89 BASIC)
Line 65: Line 65:
Here am I
Here am I
</pre>
</pre>

{{omit from|TI-89 BASIC}} <!-- Does not have a standard FFI. -->

Revision as of 20:50, 13 August 2009

Task
Use another language to call a function
You are encouraged to solve this task according to the task description, using any language you may know.

This task is inverse to the task Call foreign language function. Consider the following C program: <lang C>

  1. include <stdio.h>

extern int Query (char * Data, size_t * Length);

int main (int argc, char * argv []) {

  char     Buffer [1024];
  unsigned Size = sizeof (Buffer);
  
  if (0 == Query (Buffer, &Size))
  {
     printf ("failed to call Query\n");
  }
  else
  {
     char * Ptr = Buffer;
     while (Size-- > 0) putchar (*Ptr++);
     putchar ('\n');
  }

} </lang> Write an implementation of Query in your language and make main calling it. The function Query takes the buffer a places the string Here am I into it. The buffer size in bytes is specified by the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.

Ada

The interface package Exported specification: <lang Ada> with Interfaces.C; use Interfaces.C; with Interfaces.C.Strings; use Interfaces.C.Strings;

package Exported is

  function Query (Data : chars_ptr; Size : access size_t)
     return int;
  pragma Export (C, Query, "Query");

end Exported; </lang> The package implementation: <lang Ada> package body Exported is

  function Query (Data : chars_ptr; Size : access size_t)
     return int is
     Result : char_array := "Here am I";
  begin
     if Size.all < Result'Length then
        return 0;
     else
        Update (Data, 0, Result);
        Size.all := Result'Length;
        return 1;
     end if;
  end Query;

end Exported; </lang> With GNAT it can be built as follows: <lang sh> gcc -c main.c gnatmake -c exported.adb gnatbind -n exported.ali gnatlink exported.ali main.o -o main </lang> Sample output:

Here am I