Next: , Previous: , Up: k9: Manual  


12 Foreign Functions

python:from k import k;k('+',2,3);nodejs:k=require('k').k;k('+',2,3)
*5: ffi/import

Enterprise only

k9 is able to interface with other programing laguages (python and nodejs) via shared libraries and the foreign function interface (ffi).

12.1 python

In order to have python call k, one has to download the shared object file (k.so for linux and m.so for mac) and save it in the appropriate directory.

user1@hw1:~$ python3 -m site --user-site
/Users/user1/Library/Python/3.8/lib/python/site-packages

Once the file is stored (and it must be called k.so even on the mac) then one can start a python session and call k.

user1@hw1:~$ python3
Python 3.8.5 (v3.8.5:580fbb018f, Jul 20 2020, 12:11:27) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import k
>>> k.k('x:5?10.')
>>> k.k('x')
[7.691266643814743, 6.843659253790975, 6.399056380614638, 9.637191963847727, 4.250652831979096]
>>> len(k.k('x'))
5
>>> 

12.2 nodejs

One can call k9 from nodejs using the k.node shared libary. (If using a mac then download m.node and rename it k.node.)

From the terminal...

% node
Welcome to Node.js v14.17.4.
Type ".help" for more information.
> k=require('./k')
{}
> k.k('+/!20')
190
> 

There’s also the ability to send information from k9 to nodejs via IPC.

ipc.js file

p=1299;s=new require('net').Server();
s.listen(p, function()            {console.log(`Port ${p} is open.`);})
s.on('connection',function(socket){console.log(`Port ${p} is connected.`);
 socket.on('data',     function(chunk) {console.log(`Data: ${chunk.toString()}` );});
 socket.on('end',      function()      {console.log(`Port ${p} is disconnected.`);});
});

Start nodejs

% node ipc.js

In k9...

 h:3:1299
 h 3: "\nLine1\nLine2\n"

In nodejs...

Port 1299 is open.
Port 1299 is connected.
Data: 
Line1
Line2

12.3 ffi ⇒ 5:

Load shared library.

Contents of file ’a.c’

int add1(int x){return 1+x;}
int add2(int x){return 2+x;}
int indx(int x[],int y){return x[y];}

Compile into a shared library (done on macos here)

% clang -dynamiclib -o a.so a.c

Load the shared library into the session.

 f:"./dev/a.so"5:{add1:"i";add2:"i";indx:"Ii"}
 f[`add1] 12
13
 f[`indx][12 13 14;2]
14

12.4 import ⇒ x 5:y

Import as name x library y.

 .(:;`json;5:`json) / using dot notation

Next: Tables, Previous: I/O and Interface, Up: k9: Manual