multiwrapper.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include "ruby.h"
  2. #include "caml/callback.h"
  3. void initcaml(void) {
  4. char *dummy_argv[] = {0};
  5. caml_startup(dummy_argv);
  6. }
  7. VALUE OcamlMatrix = Qnil; // set up the Ruby namespace
  8. void Init_ocamlmatrix();
  9. VALUE singleton_matrix_new(VALUE class, VALUE width, VALUE height);
  10. void method_assign(VALUE self, VALUE x, VALUE y, VALUE item);
  11. VALUE method_retrieve(VALUE self, VALUE x, VALUE y);
  12. VALUE method_matrix_mul(VALUE self, VALUE b);
  13. void Init_ocamlmatrix() {
  14. OcamlMatrix = rb_define_module("OcamlMatrix");
  15. rb_define_singleton_method(OcamlMatrix, "w_new_matrix", singleton_matrix_new, 2);
  16. rb_define_method(OcamlMatrix, "w_matrix_assign", method_assign, 3);
  17. rb_define_method(OcamlMatrix, "w_matrix_retrieve", method_retrieve, 2);
  18. rb_define_method(OcamlMatrix, "w_matrix_mul", method_matrix_mul, 1);
  19. initcaml();
  20. }
  21. VALUE singleton_matrix_new(VALUE class, VALUE width, VALUE height) {
  22. CAMLparam0 ();
  23. CAMLlocal1 (ocaml_m);
  24. ocaml_m = ocaml_new_matrix(Val_long(NUM2LONG(width)), Val_long(NUM2LONG(height)));
  25. VALUE my_m = Data_Wrap_Struct(class, 0, 0, ocaml_m);
  26. rb_obj_call_init(my_m, 0, NULL);
  27. CAMLreturnT (VALUE, my_m);
  28. }
  29. void method_assign(VALUE self, VALUE x, VALUE y, VALUE item) {
  30. CAMLparam0 ();
  31. CAMLlocal1 (ocaml_m);
  32. Data_Get_Struct(self, value, ocaml_m);
  33. ocaml_matrix_assign(ocaml_m, Val_long(NUM2LONG(x)), Val_long(NUM2LONG(y)), Val_long(NUM2LONG(item)));
  34. CAMLreturn0;
  35. }
  36. VALUE method_retrieve(VALUE self, VALUE x, VALUE y) {
  37. CAMLparam0 ();
  38. CAMLlocal1 (ocaml_m);
  39. Data_Get_Struct(self, value, ocaml_m);
  40. VALUE retval = LONG2NUM(Long_val(ocaml_matrix_retrieve(ocaml_m,
  41. Val_long(NUM2LONG(x)),
  42. Val_long(NUM2LONG(y)))
  43. ));
  44. CAMLreturnT (VALUE, retval);
  45. }
  46. VALUE method_matrix_mul(VALUE self, VALUE b) {
  47. CAMLparam0 ();
  48. CAMLlocal3 (ocaml_m1, ocaml_m2, ocaml_m3);
  49. Data_Get_Struct(self, value, ocaml_m1);
  50. Data_Get_Struct(b, value, ocaml_m2);
  51. ocaml_m3 = ocaml_matrix_mul(ocaml_m1, ocaml_m2);
  52. VALUE my_m = Data_Wrap_Struct(class, 0, 0, ocaml_m);
  53. rb_obj_call_init(my_m, 0, NULL);
  54. CAMLreturnT (VALUE, my_m);
  55. }