<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
 
 <title>Bluish Coder: jlang</title>
 <link href="http://bluishcoder.co.nz/tag/jlang/atom.xml" rel="self"/>
 <link href="http://bluishcoder.co.nz/"/>
 <updated>2020-07-10T16:25:05+12:00</updated>
 <id>http://bluishcoder.co.nz/</id>
 <author>
   <name>Bluishcoder</name>
   <email>admin@bluishcoder.co.nz</email>
 </author>

 
 <entry>
   <title>Using the J Foreign Function Interface</title>
   <link href="http://bluishcoder.co.nz/2017/09/21/using-the-j-foreign-function-interface.html"/>
   <updated>2017-09-21T22:00:00+12:00</updated>
   <id>http://bluishcoder.co.nz/2017/09/21/using-the-j-foreign-function-interface</id>
   <content type="html">&lt;p&gt;The &lt;a href=&quot;http://jsoftware.com/&quot;&gt;J Programming Language&lt;/a&gt; is an array oriented or vector based programming language. It is in the same family of programming languages as &lt;a href=&quot;https://en.wikipedia.org/wiki/APL_(programming_language)&quot;&gt;APL&lt;/a&gt; and &lt;a href=&quot;https://en.wikipedia.org/wiki/K_(programming_language)&quot;&gt;K&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I won&#39;t be going into deep details of J syntax or a tutorial of how to use it in this post - for that I recommend something like &lt;a href=&quot;http://www.jsoftware.com/help/jforc/contents.htm&quot;&gt;J for C Programmers&lt;/a&gt; which is also available as &lt;a href=&quot;http://www.lulu.com/shop/henry-rich/j-for-c-programmers/paperback/product-4669553.html&quot;&gt;a paperback book&lt;/a&gt; - but I&#39;ll provide a quick overview of syntax used here.&lt;/p&gt;

&lt;p&gt;What I want to cover in this post is how to use the FFI to call C functions in J, and how to use callbacks from C back to J. The latter isn&#39;t well documented and I always forget how to do it.&lt;/p&gt;

&lt;h2&gt;Introduction to J&lt;/h2&gt;

&lt;p&gt;J provides a concise syntax for performing operations. Many things that would be expressed as english words in other languages use ASCII symbols in J. The &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/contents.htm&quot;&gt;J Dictionary&lt;/a&gt; and &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/vocabul.htm&quot;&gt;Vocabulary&lt;/a&gt; provides details on what these are.&lt;/p&gt;

&lt;p&gt;J has a REPL similar to Lisp environments. For a taste of J without installing it there is an &lt;a href=&quot;http://joebo.github.io/j-emscripten/full.html&quot;&gt;online J IDE&lt;/a&gt; that can be used from a browser and &lt;a href=&quot;http://code.jsoftware.com/wiki/NYCJUG/2014-12-09#Emscripten_Version_of_J&quot;&gt;details on that are here&lt;/a&gt;. Otherwise the native J system is available from &lt;a href=&quot;http://jsoftware.com/stable.htm&quot;&gt;JSoftware downloads&lt;/a&gt;. Source is &lt;a href=&quot;https://github.com/jsoftware/jsource&quot;&gt;available on github&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;J can be used as a calculator to perform operations on numbers:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  10 + 2
12
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There is no operator precedence, use brackets to define order of operations. Order of evaluation is right to left:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  3 * 4 + 10
42

  (3 * 4) + 10
22
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Sequences of numbers separated by white space are arrays of that number. Operations can be performed on arrays. To multiply each element of an array &lt;code&gt;1 2 3 4&lt;/code&gt; by &lt;code&gt;2&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  2 * 1 2 3 4
2 4 6 8
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Arrays can be multi-dimensional. One way of creating such arrays is via the &#39;&lt;a href=&quot;http://www.jsoftware.com/help/dictionary/d210.htm&quot;&gt;$&lt;/a&gt;&#39;, or Shape, operation. To create a 2x3 array:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  2 3 $ 1 2 3
1 2 3
1 2 3
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Functions are called verbs in J terminology. The &lt;code&gt;*&lt;/code&gt; and &lt;code&gt;+&lt;/code&gt; operators above are verbs. Functions that operate on verbs are called adverbs. An example is the adverb &#39;&lt;a href=&quot;http://www.jsoftware.com/help/dictionary/d420.htm&quot;&gt;/&lt;/a&gt;&#39; which inserts a verb between elements of an array and evaluates it. An example to sum an array:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  +/ 1 2 3 4
10
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;+/&lt;/code&gt; forms an operation that will do the equivalent of inserting &lt;code&gt;+&lt;/code&gt; between each element of the array like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  1 + 2 + 3 + 4
10
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Other verbs can have &lt;code&gt;/&lt;/code&gt; applied to it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  */ 1 2 3 4
24
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Verbs are monadic or dyadic. The term monadic is not related to the use of monads in languages like Haskell. It means the verb takes a single argument on the right hand side of the verb. A dyadic verb takes two arguments, one on the left and right. Many verbs have both dyadic and monadic forms. Dyadic &lt;code&gt;-&lt;/code&gt; is the subtraction operator. Monadic &lt;code&gt;-&lt;/code&gt; negates its parameter:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  10 - 5
5

  -5
_5
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;_&lt;/code&gt; character signifies a negative number to differentiate from monadic &lt;code&gt;-&lt;/code&gt;. &lt;code&gt;_5&lt;/code&gt; is negative &lt;code&gt;5&lt;/code&gt; whereas &lt;code&gt;-5&lt;/code&gt; is the application of monadic &lt;code&gt;-&lt;/code&gt; to the number &lt;code&gt;5&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A sequence of three verbs together is called a &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/intro05.htm&quot;&gt;fork&lt;/a&gt;. &#39;&lt;code&gt;+/ % #&lt;/code&gt;&#39; is a commonly demonstrated fork. It is three verbs together. The monadic &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/d400.htm&quot;&gt;&lt;code&gt;#&lt;/code&gt;&lt;/a&gt; to count the number of items in an array. The &lt;code&gt;+/&lt;/code&gt; verb which sums an array and dyadic &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/d130.htm&quot;&gt;&lt;code&gt;%&lt;/code&gt;&lt;/a&gt; which is division:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  # 1 2 3 4
4

  +/ 1 2 3 4
10

  10 % 4
2.5

  (+/ 1 2 3 4) % (# 1 2 3 4)
2.5

  (+/ % #) 1 2 3 4
2.5
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A fork of &#39;(A B C) X&#39;, where &lt;code&gt;B&lt;/code&gt; is dyadic and &lt;code&gt;A&lt;/code&gt; and &lt;code&gt;C&lt;/code&gt; are monadic does &lt;code&gt;(A X) B (C X)&lt;/code&gt;. The combination of verbs, adverbs, nouns and the right to left evaluation of J gives it a &quot;Programming with functions&quot; feel and concise syntax.&lt;/p&gt;

&lt;p&gt;J has variable assignment which can include assignment of verb sequences to named variables. &lt;code&gt;=:&lt;/code&gt; does global variable assignment and &lt;code&gt;=.&lt;/code&gt; does local variable assignment (local to the scope of verb or namespace):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  x   =: 1 2 3 4
  avg =: +/%#
  avg x
2.5
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Vales in J can be boxed or unboxed. The examples below are unboxed. They can be boxed with the &#39;&lt;a href=&quot;http://www.jsoftware.com/help/dictionary/d010.htm&quot;&gt;&lt;code&gt;&amp;lt;&lt;/code&gt;&lt;/a&gt;&#39; monadic verb. In the REPL boxed values are drawn with a box around them. To unbox a boxed value, use the monadic verb &#39;&lt;a href=&quot;http://www.jsoftware.com/help/dictionary/d020.htm&quot;&gt;&lt;code&gt;&amp;gt;&lt;/code&gt;&lt;/a&gt;&#39;. The &#39;&lt;a href=&quot;http://www.jsoftware.com/help/dictionary/d330.htm&quot;&gt;;&lt;/a&gt;&#39; varidic verb will form an array of boxed elements. For example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  a =: &amp;lt;1
  a
┌─┐
│1│
└─┘
  &amp;gt;a
1
  1;2;3;4
┌─┬─┬─┬─┐
│1│2│3│4│
└─┴─┴─┴─┘
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;All elements in an unboxed array must have the same type. Elements in boxed arrays can be different types.&lt;/p&gt;

&lt;p&gt;Hopefully that gives a taste of J syntax so the rest of this post is understandable if you don&#39;t know much of the language. I recommend playing around in the J REPL to get a feel.&lt;/p&gt;

&lt;h2&gt;Foreign Conjunctions&lt;/h2&gt;

&lt;p&gt;Calling C functions from J requires using what&#39;s called a &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/xmain.htm&quot;&gt;Foreign Conjunction&lt;/a&gt;. These are special system operations defined by the J implementation and are of the form &#39;&lt;code&gt;x !: y&lt;/code&gt;&#39; where &lt;code&gt;x&lt;/code&gt; and &#39;y&#39; are numbers. They return verbs or adverbs themselves so the result of the conjuction is applied to more arguments. An example would be the &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/dx007.htm&quot;&gt;Space&lt;/a&gt; category of foreign conjuctions that returns information about J memory usage:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  (7 !: 0) &#39;&#39;
10939904
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here &lt;code&gt;7 !: 0&lt;/code&gt; returns a verb which takes a single argument (which is ignored) and returns the number of bytes currently in use by the J interpreter.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  (7!:2) &#39;+/ 1 2 3 4&#39;
1664
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;7!:2&lt;/code&gt; returns a verb that when called with an argument returns the number of bytes required to execute that argument as a J sentence.&lt;/p&gt;

&lt;p&gt;There&#39;s lots more described in the &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/xmain.htm&quot;&gt;Foreign Conjunction&lt;/a&gt; documentation which allows reflecting an introspecting on just about everything in the J system.&lt;/p&gt;

&lt;h2&gt;Foreign Function Interface&lt;/h2&gt;

&lt;p&gt;The foreign function interface is the set of foreign conjunctions where the left side of the conjunction verb is the number &lt;code&gt;15&lt;/code&gt;. There&#39;s a short list of these in the &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/dx015.htm&quot;&gt;Dynamic Link Library&lt;/a&gt; part of the dictionary, and further explanation in the &lt;a href=&quot;http://www.jsoftware.com/help/user/dlls.htm&quot;&gt;Dlls&lt;/a&gt; section of the user manual. There are more verbs than are listed in these pages and the J source file &lt;a href=&quot;https://github.com/jsoftware/jsource/blob/master/jsrc/x15.c&quot;&gt;x15.c&lt;/a&gt; gives an idea of the scope. Most of the additional ones are used in implementation of the J library but we have to delve into undocumented features to handle C callbacks.&lt;/p&gt;

&lt;p&gt;The J source file &lt;a href=&quot;https://github.com/jsoftware/jsource/blob/95c43476358f5c385560a72b7cfe395d446e8f4c/jlibrary/system/main/stdlib.ijs#L478&quot;&gt;stdlib.ijs&lt;/a&gt; contains the definitions for names that make the foreign conjunctions easier to use. The ones covered in this post are:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cd    =: 15!:0
memr  =: 15!:1
memw  =: 15!:2
mema  =: 15!:3
memf  =: 15!:4
cdf   =: 15!:5
cder  =: 15!:10
cderx =: 15!:11
cdcb  =: 15!:13
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To call a foreign function we use the &#39;&lt;code&gt;15!:0&lt;/code&gt;&#39; verb, defined as &lt;code&gt;cd&lt;/code&gt; in the standard library. This is described in the documentation as &#39;Call DLL Function&#39; and is documented in the &lt;a href=&quot;http://www.jsoftware.com/help/user/call_procedure.htm&quot;&gt;Calling DLLs&lt;/a&gt; section of the user manual. It is dyadic and has the form:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&#39;filename procedure [&amp;gt;] [+] [%] declaration&#39; cd parameters
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The descriptions below look complicated but will become clearer with a few examples.&lt;/p&gt;

&lt;p&gt;The first argument is a string that contains the function name and arguments it takes. It&#39;s the declaration of the function basically. The second parameter is an array of the arguments that the foreign function takes.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;filename&lt;/code&gt; is the name of a DLL or shared library. It can also be one of the following special filenames:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;0&lt;/code&gt; = If filename is &lt;code&gt;0&lt;/code&gt; then the &#39;procedure&#39; is a signed integer representing a memory address for where the function is located.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;1&lt;/code&gt; = If filename is &lt;code&gt;1&lt;/code&gt; then the &#39;procedure&#39; is a non-negative integer that is the index of a procedure in a vtable. The first element of the parameter array should be an address of the address of the vtable, the &#39;object&#39; address. The declaration of the first parameter should be &#39;&lt;code&gt;*&lt;/code&gt;&#39; or &#39;&lt;code&gt;x&lt;/code&gt;&#39;. This is used for calling COM objects or Java Native Interface objects.&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;The &lt;code&gt;procedure&lt;/code&gt; is the name of the function in the DLL or shared library to call. It can also be a number as described in the &lt;code&gt;filename&lt;/code&gt; portion above.&lt;/p&gt;

&lt;p&gt;The &#39;&lt;code&gt;&amp;gt;&lt;/code&gt;&#39;, &#39;&lt;code&gt;+&lt;/code&gt;&#39; and &#39;&lt;code&gt;%&lt;/code&gt;&#39; parts are optional and define attributes of the function:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&#39;&lt;code&gt;&amp;gt;&lt;/code&gt;&#39; = The procedure returns a scalar result. Without &#39;&lt;code&gt;&amp;gt;&lt;/code&gt;&#39; the result is an array containing the boxed scalar result with the possibly modified list of boxed arguments appended to it.&lt;/li&gt;
&lt;li&gt;&#39;&lt;code&gt;+&lt;/code&gt;&#39; = Chooses the calling convention of the fnuction. On Windows the standard calling convention is &lt;code&gt;__stdcall&lt;/code&gt; and using &#39;&lt;code&gt;+&lt;/code&gt;&#39; selects &lt;code&gt;__cdecl&lt;/code&gt;. On Unix using &#39;&lt;code&gt;+&lt;/code&gt;&#39; has no effect.&lt;/li&gt;
&lt;li&gt;&#39;&lt;code&gt;%&lt;/code&gt;&#39; = Does a floating point reset after the call. Some procedures leave floating point in an invalid state.&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;&#39;declaration&#39; is a string of blank delimited characters defining the types of the arguments passed to the function, and the type of the result. They can be:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;c&lt;/code&gt; = J character (1 byte)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;w&lt;/code&gt; = J literal2 (2 byte)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;u&lt;/code&gt; = J literal4 (4 byte)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;s&lt;/code&gt; = short integer (2 byte)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;i&lt;/code&gt; = integer (4 byte)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;l&lt;/code&gt; = long integer (8 byte)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;x&lt;/code&gt; = J integer (4 or 8 byte depending on 32/64 bit architecture)&lt;/li&gt;
&lt;li&gt;&#39;f&#39; = short float (4 byte)&lt;/li&gt;
&lt;li&gt;&#39;d&#39; = J float (8 byte)&lt;/li&gt;
&lt;li&gt;&#39;j&#39; = J complex (16 byte - 2 d values) (pointer only, not as result or scalar)&lt;/li&gt;
&lt;li&gt;&#39;*&#39; = pointer. This can be followed by any of the above to indicate the type pointed to. A parameter passed in the place where a pointer is expected can be a J array of the right type, or a scalar boxed scalar integer that is a memory address.&lt;/li&gt;
&lt;li&gt;&#39;n&#39; = no result (result is ignored and &#39;0&#39; is returned)&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;The first entry in the &#39;declaration&#39; is the result type and the remaining ones describe each parameter provided in the second argument to &#39;&lt;code&gt;cd&lt;/code&gt;&#39;.&lt;/p&gt;

&lt;p&gt;The &#39;parameters&#39; argument to &#39;&lt;code&gt;cd&lt;/code&gt;&#39; should be a boxed array. If it is not boxed then it will be boxed for you.&lt;/p&gt;

&lt;h2&gt;Examples&lt;/h2&gt;

&lt;p&gt;The following example calls the C function &lt;code&gt;puts&lt;/code&gt; from J on my Linux OS:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  &#39;/lib/x86_64-linux-gnu/libc.so.6 puts x *c&#39; cd &amp;lt;&#39;hello&#39;
┌─┬─────┐
│6│hello│
└─┴─────┘
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The full path to the shared library is given with &lt;code&gt;puts&lt;/code&gt; as the function name. The &#39;declaration&#39; is set to return a J integer and marks the function as taking a pointer to characters as an argument. We pass the boxed array of characters with &lt;code&gt;&amp;lt;&#39;hello&#39;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The result is an boxed array where the first element is the value returned from the function. This is &lt;code&gt;6&lt;/code&gt;, the number of characters printed. The rest of the result is the arguments passed to the function. The output of &lt;code&gt;puts&lt;/code&gt; can be seen on the console.&lt;/p&gt;

&lt;p&gt;If we just want the result of the function, without the appended list of parameters, then we can use the &#39;&lt;code&gt;&amp;gt;&lt;/code&gt;&#39; attribute in the first argument to &#39;&lt;code&gt;cd&lt;/code&gt;&#39;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  &#39;/lib/x86_64-linux-gnu/libc.so.6 puts &amp;gt; x *c&#39; cd &amp;lt;&#39;hello&#39;
6
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Loading shared libraries using &lt;code&gt;cd&lt;/code&gt; uses system resources. To unload shared libraries currently in use by J use the &#39;&lt;code&gt;15!:5&lt;/code&gt;&#39; foreign conjunction, or &lt;code&gt;cdf&lt;/code&gt;. It is monadic and ignores its argument:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  cdf &#39;&#39;
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Errors&lt;/h2&gt;

&lt;p&gt;If the shared library can&#39;t be found, or there is some other problem with the call, then a &#39;domain error&#39; will result:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  &#39;doesnotexist.so puts &amp;gt; x *c&#39; cd &amp;lt;&#39;hello&#39;
|domain error
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To find the reason for the domain error, use the &#39;&lt;code&gt;15!:10&lt;/code&gt;&#39; Foreign Function verb to identify the error. If is a monadic verb that ignores its argument and prints out information about a &lt;code&gt;domain error&lt;/code&gt;. In the standard library the name &lt;code&gt;cder&lt;/code&gt; is assigned to &#39;&lt;code&gt;15!:10&lt;/code&gt;&#39;. The meaning of &lt;a href=&quot;http://www.jsoftware.com/help/user/cd_domain_error.htm&quot;&gt;what it returns&lt;/a&gt; is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;0 0 = no error&lt;/li&gt;
&lt;li&gt;1 0 = file not found&lt;/li&gt;
&lt;li&gt;2 0 = procedure not found&lt;/li&gt;
&lt;li&gt;3 0 = too many DLLs loaded (max 20)&lt;/li&gt;
&lt;li&gt;4 0 = too many or too few parameters&lt;/li&gt;
&lt;li&gt;5 x = declaration x invalid&lt;/li&gt;
&lt;li&gt;6 x = parameter x type doesn&#39;t match declaration&lt;/li&gt;
&lt;li&gt;7 0 = system limit - linux64 max 8 float/double scalars&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;In the example above it indicates &#39;file not found&#39;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  cder &#39;&#39;
1 0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For a detailed description of the error use &#39;&lt;code&gt;15!:11&lt;/code&gt;&#39;, or &lt;code&gt;cderx&lt;/code&gt;. It is monadic, ignores its arguments, and returns a boxed array with the error number as the first element and a string description as the second:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  &#39;doesnotexist.so puts &amp;gt; x *c&#39; cd &amp;lt;&#39;hello&#39;
|domain error: cd
|   &#39;doesnotexist.so puts &amp;gt; x *c&#39;    cd&amp;lt;&#39;hello&#39;

   cderx &#39;&#39;
┌─┬──────────────────────────────────────────────────────────────────────────┐
│0│doesnotexist.so: cannot open shared object file: No such file or directory│
└─┴──────────────────────────────────────────────────────────────────────────┘
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Memory&lt;/h2&gt;

&lt;p&gt;To allocate, free, read and write C memory in J requires use of the &lt;a href=&quot;http://www.jsoftware.com/help/user/memory_management.htm&quot;&gt;memory management&lt;/a&gt; foreign verbs.  An example of an FFI call that returns a string is &lt;code&gt;getenv&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  &#39;/lib/x86_64-linux-gnu/libc.so.6 getenv *c *c&#39; cd &amp;lt;&#39;HOME&#39;
┌───────────────┬────┐
│140735847611736│HOME│
└───────────────┴────┘
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note here that the returned value is a number. This represents a pointer to the string that &lt;code&gt;getenv&lt;/code&gt; returns. To see the string result from this pointer we need to use the J verb that deals with reading raw memory.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  memr 140735847611736 0 _1 2
/home/myuser
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&#39;&lt;code&gt;15!:1&lt;/code&gt;&#39;, or &lt;code&gt;memr&lt;/code&gt; as it is defined in the standard library, reads raw memory. It takes an array as an argument with the elements of the array being:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The numeric pointer to the memory&lt;/li&gt;
&lt;li&gt;The offset into that memory&lt;/li&gt;
&lt;li&gt;The number of elements to read. A &lt;code&gt;_1&lt;/code&gt; means read to the first NUL byte which is useful for C strings and is used in this &lt;code&gt;getenv&lt;/code&gt; example.&lt;/li&gt;
&lt;li&gt;An optional type argument for the data to be read. The default is &lt;code&gt;2&lt;/code&gt; which is used explicitly above. It can be 2, 4, 8 or 16 for char, integer, float or complex respectively. The count parameter is number of elements of the given type - it takes the size into account.&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;&#39;&lt;code&gt;15!:3&lt;/code&gt;&#39;, or &lt;code&gt;mema&lt;/code&gt;, allocates memory. It takes a length argument for number of bytes to allocate and returns &lt;code&gt;0&lt;/code&gt; on allocation failure:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  mema 1024
23813424
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The numeric result return is a pointer address that can be passed to &#39;&lt;code&gt;*&lt;/code&gt;&#39; parameters in the FFI calls.&lt;/p&gt;

&lt;p&gt;&#39;&lt;code&gt;15!:4&lt;/code&gt;&#39;, or &lt;code&gt;memf&lt;/code&gt;, frees memory allocated with &lt;code&gt;mema&lt;/code&gt;. It takes the address as an argument and returns &#39;0&#39; on success or &#39;1&#39; on failure:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  memf 23813424
0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&#39;&lt;code&gt;15!:2&lt;/code&gt;&#39;, or &lt;code&gt;memw&lt;/code&gt;, writes to memory given a pointer. It is the inverse of &lt;code&gt;memr&lt;/code&gt; and is dyadic. The left hand argument is an array of data to write, the right hand argument similar to that defined by &lt;code&gt;memr&lt;/code&gt; above:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  mema 32
22371984

  &#39;hello&#39; memw 22371984 0 6 2
  memr 22371984 0 _1 2
hello

  &#39;/lib/x86_64-linux-gnu/libc.so.6 puts &amp;gt; x *c&#39; cd &amp;lt;&amp;lt;22371984
6

  memf 22371984
0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice the double boxing of the pointer argument to the &lt;code&gt;puts&lt;/code&gt; call. This is what enables J to recognise it as a pointer parameter rather than an integer argument. It is a boxed array containing a boxed integer.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;count&lt;/code&gt; argument passed to the &lt;code&gt;memw&lt;/code&gt; call can be one greater than the length of the string in the left argument if the type of the &lt;code&gt;memw&lt;/code&gt; call is &lt;code&gt;2&lt;/code&gt; (the char type). In that case a NUL byte is appended which is what we use in the example above.&lt;/p&gt;

&lt;p&gt;Here&#39;s another example using &lt;code&gt;sprintf&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  mema 1024
24110208

  &#39;/lib/x86_64-linux-gnu/libc.so.6 sprintf &amp;gt; x * *c *c x&#39; cd (&amp;lt;24110208);&#39;string is: %s %d\n&#39;;&#39;foo&#39;;42
17

  memr 24110208 0 _1
string is: foo 42

  memf 24110208
0
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Callbacks&lt;/h2&gt;

&lt;p&gt;The foreign function conjunction &#39;&lt;code&gt;15!:13&lt;/code&gt;&#39;, or &lt;code&gt;cdcb&lt;/code&gt;, is used for defining a callback function that can be passed to a C function and have it call back to J. It is a monadic verb that takes a number as an argument for the number of arguments that the callback function uses. It returns a pointer to a compiled function that can be used as the callback.&lt;/p&gt;

&lt;p&gt;When that function is called it will do argument conversion and call a J verb called &lt;code&gt;cdcallback&lt;/code&gt; with the arguments passed as a boxed array. The following demonstrates how this works by defining some callback functions with a definition of &lt;code&gt;cdcallback&lt;/code&gt; that prints its output to the REPL:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cdcallback =: monad define
  y (1!:2) 2
  0
)

f1 =: cdcb 1
f2 =: cdcb 2
f3 =: cdcb 3

  (&#39;0 &#39;,(&quot;: f1),&#39; &amp;gt; n x&#39;) cd &amp;lt;100
100
0

   (&#39;0 &#39;,(&quot;: f2),&#39; &amp;gt; n x x&#39;) cd 100;200
100 200
0

   (&#39;0 &#39;,(&quot;: f3),&#39; &amp;gt; n x x x&#39;) cd 100;200;300
100 200 300
0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this example &lt;code&gt;cdcallback&lt;/code&gt; is implemented as a monadic function that passes its argument, &#39;&lt;code&gt;y&lt;/code&gt;&#39;, to the foreign conjunction &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/dx001.htm&quot;&gt;for writing to the screen&lt;/a&gt;, &#39;&lt;code&gt;1!:2&lt;/code&gt;&#39;. It returns &#39;0&#39; as a result.&lt;/p&gt;

&lt;p&gt;Three callback functions are created for one, two and three arguments respectively. These return C pointers to the equivalent of:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;int f1(int);
int f2(int, int);
int f3(int, int, int);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then we call the functions using &lt;code&gt;cd&lt;/code&gt;. The declaration string is built dynamically by concatenating the function address into it. This uses the &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/d602.htm&quot;&gt;default format monadic verb&lt;/a&gt;, &#39;&lt;code&gt;&quot;:&lt;/code&gt;&#39;. Note how the first parameter in the delcaration string is &#39;&lt;code&gt;0&lt;/code&gt;&#39;, which as described above means a function pointer is expected instead of a function name. That&#39;s what we&#39;re concatenating in:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  (&#39;0 &#39;,(&quot;: f1),&#39; &amp;gt; n x&#39;)
0 140277582398804 &amp;gt; n x
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Calling the callback function prints to the screen the argument array. Knowing this we can start to test with a function that requires a callback. For that example I&#39;ll use the &lt;code&gt;qsort&lt;/code&gt; C function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;void qsort(void *base, size_t nmemb, size_t size,
           int (*compar)(const void *, const void *));
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can test with our existing callback that just displays the argument output:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  &#39;/lib/x86_64-linux-gnu/libc.so.6 qsort n *l x x *&#39; cd (1 2 3 4);4;8;&amp;lt;&amp;lt;f2
30492672 30492676
30492680 30492684
30492672 30492680
30492676 30492680
0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For qsort I&#39;ve defined it as taking an array of integers, an integer for the number of members, an integer for the size of each member and a pointer. For arguments I pass an array of integers (the J array is automatically converted to a C array), &#39;4&#39; for the number of members, &#39;8&#39; for the size of each member (eight bytes each) and a boxed number for the pointer to the callback function that takes two arguments.&lt;/p&gt;

&lt;p&gt;When run it prints out the two arguments each time the callback is called. Because &lt;code&gt;qsort&lt;/code&gt; expects the callback to take pointers as arguments they appear as integers. Now we need to write a callback that dereferences those arguments and returns the result of a comparison.&lt;/p&gt;

&lt;p&gt;We can use &lt;code&gt;memr&lt;/code&gt; to read the integer value from memory and the &#39;&lt;a href=&quot;http://www.jsoftware.com/help/dictionary/d520.htm&quot;&gt;{&lt;/a&gt;&#39; dyadic verb to retrieve elements from the array (&#39;&lt;code&gt;x { y&lt;/code&gt;&#39; returns the xth element of y).&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  cdcallback =: monad define
    lhs =. 0 { y
    rhs =. 1 { y
    i1 =. memr lhs,(0 1 4)
    i2 =. memr rhs,(0 1 4)
    diff =. i1 - i2
    (i1,i2,diff) (1!:2) 2
    if. diff &amp;lt; 0 do. diff =. _1
    elseif. diff &amp;gt; 0 do. diff =. 1
    end.
    diff
  )
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Running this with our &lt;code&gt;qsort&lt;/code&gt; call gives:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  &#39;/lib/x86_64-linux-gnu/libc.so.6 qsort &amp;gt; n *l x x *&#39; cd (3 7 1 4);4;8;&amp;lt;&amp;lt;f2
3 7 _4
1 4 _3
3 1 2
3 4 _1
7 4 3
0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This looks good! But how do we get the result back? &lt;code&gt;qsort&lt;/code&gt; modifies in place, and when converting array arguments J will copy the array to a C array and then copy the results back. To look at the results we need to remove the &#39;&gt;&#39; attribute in the declaration to view the modified parameters:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  &#39;/lib/x86_64-linux-gnu/libc.so.6 qsort n *l x x *&#39; cd (3 7 1 4);4;8;&amp;lt;&amp;lt;f2
3 7 _4
1 4 _3
3 1 2
3 4 _1
7 4 3
┌─┬───────┬─┬─┬─────────────────┐
│0│1 3 4 7│4│8│┌───────────────┐│
│ │       │ │ ││140277582398867││
│ │       │ │ │└───────────────┘│
└─┴───────┴─┴─┴─────────────────┘
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The second element of the boxed array is the sorted array. Some points to note:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Notice the use of the &lt;code&gt;if.&lt;/code&gt;, &lt;code&gt;else.&lt;/code&gt;, &lt;code&gt;end.&lt;/code&gt; control structure in the callback. I couldn&#39;t get it to work returning the result of the subtraction of &lt;code&gt;i1 - i2&lt;/code&gt;. This resulted in the callback always returning zero. I think there may be some number conversion issue happening with &lt;code&gt;diff&lt;/code&gt; not being an integer. Assigning a specific integer resolved this.&lt;/li&gt;
&lt;li&gt;The callback could be written more concisely using other J features but I wanted to keep it readable given only what was covered in the introduction of this post.&lt;/li&gt;
&lt;li&gt;Dealing with integer sizes, pointers as integers, and all the conversions going on makes things crash if you get the types wrong.&lt;/li&gt;
&lt;li&gt;I defined &lt;code&gt;cdcallback&lt;/code&gt; as a global variable by using &lt;code&gt;=:&lt;/code&gt; as the assignment verb. Using &lt;code&gt;=.&lt;/code&gt; would make a local variable. This enables creating a local callback, within the scope of another verb or namespace, just before passing it to the function that requires it.&lt;/li&gt;
&lt;li&gt;If you need multiple callbacks that do different things active at the same time you need to write the one &lt;code&gt;cdcallback&lt;/code&gt; and differentiate inside that somehow, maybe based on the number or type of arguments, to decide what action needs to be performed.&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Using the FFI from J isn&#39;t difficult but requires care. Using callbacks is more complicated and not very well documented but it&#39;s possible. Searching the example J code for &lt;code&gt;cdcb&lt;/code&gt; or &lt;code&gt;15!:13&lt;/code&gt; will find example usage. There are other undocumented FFI routines but I haven&#39;t looked into them yet.&lt;/p&gt;

&lt;p&gt;For more information on J, including tutorials, books, mailing lists, etc there is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://jsoftware.com/&quot;&gt;JSoftware&lt;/a&gt;, the makers of the J system.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.jsoftware.com/help/primer/contents.htm&quot;&gt;J Primer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.jsoftware.com/help/phrases/contents.htm&quot;&gt;J Phrases&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.jsoftware.com/help/dictionary/contents.htm&quot;&gt;J Dictionary&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.jsoftware.com/help/learning/contents.htm&quot;&gt;Learning J&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.jsoftware.com/help/jforc/contents.htm&quot;&gt;J for C programmers&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.jsoftware.com/help/dictionary/vocabul.htm&quot;&gt;J Vocabulary&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.reddit.com/r/apljk/&quot;&gt;/r/apljk&lt;/a&gt; on reddit.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://rosettacode.org/wiki/Category:J&quot;&gt;Rosetta Code J Language&lt;/a&gt; has lots of examples in J.&lt;/li&gt;
&lt;/ul&gt;

</content>
 </entry>
 
 
</feed>
