Use another language to call a function: Difference between revisions
Content deleted Content added
+ D entry |
|||
Line 148: | Line 148: | ||
$ |
$ |
||
</lang> |
</lang> |
||
=={{header|D}}== |
|||
This shows how to perform the task on Windows. Elsewhere the procedure is very similar. |
|||
First write a D module like this, named "query_func.d": |
|||
<lang d>import core.stdc.string; |
|||
extern(C) bool query(char *data, size_t *length) pure nothrow { |
|||
immutable text = "Here am I"; |
|||
if (*length < text.length) { |
|||
*length = 0; // Also clears length. |
|||
return false; |
|||
} else { |
|||
memcpy(data, text.ptr, text.length); |
|||
*length = text.length; |
|||
return true; |
|||
} |
|||
}</lang> |
|||
Generate a library file with: |
|||
<pre>dmd -lib query_func.d</pre> |
|||
This generates a <code>query_func.lib</code> file. |
|||
Then create a C file named "mainc.c", given in the task description and here improved a little: |
|||
<lang c>#include <stdio.h> |
|||
#include <stdbool.h> |
|||
extern bool query(char *data, size_t *length); |
|||
int main() { |
|||
char buffer[1024]; |
|||
size_t size = sizeof(buffer); |
|||
if (query(buffer, &size)) |
|||
printf("%.*s\n", size, buffer); |
|||
else |
|||
puts("The call to query has failed."); |
|||
return 0; |
|||
}</lang> |
|||
Then you can compile and link all with the [http://www.digitalmars.com/download/freecompiler.html DMC C compiler](on Linux you can use GCC): |
|||
<pre>dmc query_func.lib mainc.c</pre> |
|||
It generates the "mainc.exe" binary, that prints the desired output: |
|||
<pre>Here am I</pre> |
|||
=={{header|Delphi}}== |
=={{header|Delphi}}== |