Skip to content

FFI interface examples


Rmath library

Bindings to Rmath using FFI for kdb+

Rmath provides the routines supporting the distribution and special (e.g. Bessel, beta and gamma functions) functions in R.

Prerequisites :

  • stand-alone Rmath library
  • FFI for kdb+

Install Rmath according to the platform you are using. For example;

sudo apt-get install r-mathlib
sudo yum install libRmath

Generate 100K numbers from normal distribution:

q)// Bind rnorm function
q).rm.rnorm:.ffi.bind[``rnorm; "jff"; "f"]
q)// Bind set_seed function
q).rm.set_seed:.ffi.bind[``set_seed; "ii"; " "]
q)// Set random seed
q).rm.set_seed (456i; 789i; ::)
q)do[100000; gen:.rm.rnorm (1; 0f; 1f; ::); if[-9h ~ type gen; norms,: gen]]
q)// verify that avg and dev are 0 and 1
q)(avg; dev) @\: norms
0.003488721 1.002219

Standard C library

q)// Buffer
q)buffer: 80#"\000"

q)// Write to buffer and return the number of bytes written
q)args:(buffer; "%s %.4f %hd\000"; "example\000"; 3.16f; 144000h; ::)
q)n:.ffi.callFunction[("i"; `sprintf)] args

q)// Show the written characters
q)buffer til n
"example 3.1600 32767"

q)// Bind qsort function
q).cstdlib.qsort:.ffi.bind[`qsort; "liik"; " "];

q)// Callback function
q)cmp:{0N!"compare: ",.Q.s x,y; (x>y)-x<y};
q)seq:3 1 2i

q).cstdlib.qsort (seq; `int$count seq; 4i; (cmp; "II"; "i"); ::)
"compare: 1 2i\n"
"compare: 3 1i\n"
"compare: 3 2i\n"

1 2 3i

q).cstdlib.qsort (seq; `int$count seq; 1i; (cmp; "BB"; "i"); ::)
"compare: 01b\n"
"compare: 10b\n"
"compare: 11b\n"


q)// symbols are pointers - size of pointer is .ffi.ptrsize[]
q).cstdlib.qsort (seq; `int$count seq; .ffi.ptrsize[]; (cmp; "SS"; "i"); ::)
"compare: `a`b\n"
"compare: `c`a\n"
"compare: `c`b\n"

Back to top