Creating a shared Haskell Lib

From OpenCog
Jump to: navigation, search

This is an explanation on how to use Haskell to create Libraries that can be called from the Atomspace which you obviously have to have installed. It can also easily be translated into a library that can then be called directly from C/C++.

Example Library

This [1] repo contains the code for a minimal example of such a Library. We will go over all the interesting files in this project.

File1: Lib.hs

First let's look at the actually haskell code:

 import OpenCog.AtomSpace
 import Foreign.C
 import Foreign.Ptr

This is the miminal set of imports needed

 someFunc :: Atom -> AtomSpace Atom
 someFunc a = return $ Link "SetLink" [a,a] noTv

This function does the actually work. It gets an Atom as the input. And in this case, it just duplicates the that and wraps in a SetLink. Then returning this as the result.

 foreign export ccall "someFunc"
     c_func :: Ptr AtomSpaceRef -> Handle -> IO (Handle)
 
 c_func = exportFunction someFunc

Here we export the function so it is visible/callable from for Example C. The 'exportFunction' function takes the someFunc does all the conversion from the C++ to the Haskell representation and runs it.

The types of all the functions have to be exactly as shown here, altho you could create your own way of getting the c_func in case the type signature of someFunc doesn't work for your purpose.

File2: Stack.yaml

There are 3 interesting lines in the stack.yaml file.

extra-deps: [opencog-atomspace-0.1.0.7]
#- location: '/home/roman/OpenCog/atomspace/opencog/haskell'
extra-lib-dirs: [/usr/local/lib/opencog]

The first 2 are ways to get the OpenCog.AtomSpace module. If there is a new version of the Haskell Bindings you will need to update the version number in the extra-deps. If you are also working on the Haskell Bindings at the same time you are creating this library. Switching to the second option might be easier during development, just change the path to point to your location of the atomspace repo.

The 3rd tell the compiler where to find the libatomspace-cwrapper.so

File3: hsbracket.c

The hsbracket.c file serves the purpose of automatically calling hs_init() and hs_exit() so that this doesn't have to be done manually.

Installing

After creating your library run ./install.sh. This will build the project and install the library to /usr/local/lib/opencog/libLIBNAME-VERSION.so where LIBNAME is the name of your lib and VERSION the version.

Using/Testing

Either using guile or the cogserver create the following Link an execute it.

 ExecutionOutputLink
   GroundedSchemaNode "lib: WHOLELIBNAME\\FUNCTIONNAME"
   ListLink
     ConceptNode "test"

in the case of the demo lib the GSN would be "lib: libopencoglib\\someFunc"