Skip to content

Instantly share code, notes, and snippets.



Last active Mar 29, 2017
What would you like to do?
How to wrap a C struct in a ruby extension
#include "ruby.h"
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) {
// 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