haskell-numerics / hmatrix

Linear algebra and numerical computation
381 stars 104 forks source link

Make FFI usage possible for the uninitiated? #230

Open mbwgh opened 7 years ago

mbwgh commented 7 years ago

Hello,

is it possible to use hmatrix types, for instance a Matrix Double, in conjunction with the foreign function interface in a more straight-forward manner? As it is now, a lot of the Devel module is undocumented, and the example given in the examples directory is unidiomatic on both the C and the Haskell side, in my humble opinion. I understand that a function of type Matrix a -> (Ptr a -> IO b) -> IO b may not really make sense because of layout and offset issues, but having to rely on some obscure undocumented combinators makes the library hard to use.

To make the issue a little more concrete: I have a C function of type void (double *restrict a, double const *restrict b, int n), where a is R^(NxN), and b is R^(NxNxNxN), represented by a UArray (Int, Int, Int, Int) Double on the Haskell side. The matrix a is going to be modified, and assumed (non-trivially) initialized. While I can use unsafeThaw and withStorableArray on the array b, it is not clear to me how to make this work with the matrix a.

Hopefully, I didn't miss something obvious. Thanks in advance!

albertoruiz commented 7 years ago

Sorry, I don't have much time at the moment for working on this. I tried to generate some useful wrapping tools, especially for lapack. Perhaps you can find some piece of code in that module that is useful for you. And, in any case, I would be happy to receive contributions for alternative wrapping utilities.

mbwgh commented 7 years ago

For what it's worth, looking at the implementation of flatten, it seems this is an O(1) operation if the matrix is RowMajor and no slicing has taken place. This at least gives access to the FFI of the vector library, allowing judicious use of unsafeThaw and unsafeWith for instance.