Call a foreign-language function: Difference between revisions

+Stata (call C)
(+Stata (call C))
Line 1,819:
 
=={{header|Stata}}==
=== Calling C ===
It's possible to call a C program from Stata using the a '''[https://www.stata.com/plugins/ plugin]'''. A plugin is a C program that is compiled to a DLL, then used as any other command in Stata after being loaded.
 
As an example let's build a '''[https://en.wikipedia.org/wiki/Hilbert_matrix Hilbert matrix]''' in C.
 
<lang c>#include <stdlib.h>
#include "stplugin.h"
 
STDLL stata_call(int argc, char *argv[])
{
int i, j, n = strtol(argv[1], NULL, 0);
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
// Don't forget array indices are 1-based in Stata.
SF_mat_store(argv[0], i, j, 1.0/(double)(i+j-1));
}
}
return 0;
}</lang>
 
The DLL can be built from Visual Studio, or in the console with '''cl /LD hilbertmat.c stplugin.c'''.
 
Declare also an ADO file to call the plugin:
 
<lang stata>program hilbert
matrix define `1'=J(`2',`2',0)
plugin call hilbertmat, `1' `2'
end
 
program hilbertmat, plugin</lang>
 
Then, you may call
 
<lang stata>. hilbert mymat 4
 
. matrix list mymat
 
symmetric mymat[4,4]
c1 c2 c3 c4
r1 1
r2 .5 .33333333
r3 .33333333 .25 .2
r4 .25 .2 .16666667 .14285714</lang>
 
Notice the program as is has minimal protection against invalid arguments. Production code should be more careful.
 
=== Calling Java ===
It's possible to call a Java program from Stata using the '''[https://www.stata.com/help.cgi?javacall javacall]''' command. Using the '''[https://www.stata.com/java/api15/ Stata Java API]''', one can access the current dataset, matrices, macros...
Line 1,833 ⟶ 1,880:
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
// Unlike Stata and the C API, indices are 0-based in the Java API.
Matrix.storeMatrixAt(args[0], i, j, 1.0/(double)(i+j+1));
}
1,336

edits