Skip to content

Instantly share code, notes, and snippets.

@DCrow
Last active March 29, 2017 16:29
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 DCrow/6d66575a5676f98c653d7a48fb24c57a to your computer and use it in GitHub Desktop.
Save DCrow/6d66575a5676f98c653d7a48fb24c57a to your computer and use it in GitHub Desktop.
How to wrap a C struct in a ruby extension
#include "ruby.h"
// http://www.angelfire.com/electronic2/issac/rb_cpp_ext_tut.txt
typedef VALUE (ruby_method)(...);
VALUE DeviceDriver = Qnil;
struct conn {
VALUE settings;
connection *conn_ptr;
};
// Release memory used by struct
extern "C" void device_driver_free(conn *connection) {
free(connection);
}
// Allocate needed memory for struct
extern "C" VALUE device_driver_alloc(VALUE self) {
struct conn *connection = (conn*)malloc(sizeof(struct conn));
return Data_Wrap_Struct(self, NULL, device_driver_free, connection);
}
// A basic initializer
extern "C" VALUE method_initialize(VALUE self, VALUE settings) {
conn *connection;
Data_Get_Struct(self, conn, connection);
connection->settings = settings;
return self;
}
// Метод который объявляет весь модуль
extern "C" void Init_device_driver() {
DeviceDriver = rb_define_class("DeviceDriver", rb_cObject);
rb_define_alloc_func(DeviceDriver, alloc_device_driver);
// When transcompiling cpp to c code ruby_method macro has to be used
// for correct compiling
rb_define_method(DeviceDriver, "initialize", (ruby_method*) &method_initialize, 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment