Use another language to call a function: Difference between revisions
New task + solution |
m Category {{task|Programming environment operations}} |
||
Line 1:
{{task|Programming environment operations}}
This task is inverse to the task [[Call foreign language function]]. Consider the following [[C]] program:
<lang C>
|
Revision as of 13:49, 11 August 2009
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
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>
- 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