Skip to content

Instantly share code, notes, and snippets.

@v0dro
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save v0dro/e0aff8e9c9c898a18091 to your computer and use it in GitHub Desktop.
Save v0dro/e0aff8e9c9c898a18091 to your computer and use it in GitHub Desktop.
Writing a C function for NMatrix
You first have a function say `__solve__` being called from ruby code.
You then declare the equivalent C function that will be called from the C code that will be executed when `__solve__` is called.
These declarations (which look like `rb_define_function_blah_blah`) are kept inside a function called `void Init_nmatrix()` in the file `ruby_nmatrix.c`.
Say the C function is called `nm_solve`, then the declaration looks like `rb_define_private_method(cNMatrix, "__solve__", (METHOD)nm_solve, 4);`.
This `nm_solve` function should be declared in the file `ruby_nmatrix.c`.
Then you have a function called `nm_solve` in math.cpp whose sole function is to take shit (arguments) from `__solve__`, make sense of them (if any) and then call a C function called `nm_math_solve` whose sole job is to do the `ttable` stuff, and with those helpful macros, generate a C++ function call of the appropriate data type.
The `nm_math_solve` function is a C++ function (placed in math.cpp) so it should be placed in an `extern "C"` block in `math.h`.
The generated function is implemented in `math.cpp` under a namespace, say `nm::math` and its name is `solve`.
This is a templated function, so that the function call generated by the ttable shizzle will pass values into this function with the appropriate data type, which the template will figure out on its own.
It is HERE that your actual program logic will be written.
You will mostly pass an arg into this function which will be directly modified, instead of returning things and converting between C and Ruby data later.
Phew.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment