Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a helper method for reading/writing memory #123

Merged
merged 3 commits into from
Mar 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions ext/fiddle/pointer.c
Original file line number Diff line number Diff line change
Expand Up @@ -799,6 +799,33 @@ rb_fiddle_ptr_s_to_ptr(VALUE self, VALUE val)
return ptr;
}

/*
* call-seq:
* Fiddle::Pointer.read(address, len) => string
*
* Or read the memory at address +address+ with length +len+ and return a
* string with that memory
*/

static VALUE
rb_fiddle_ptr_read_mem(VALUE klass, VALUE address, VALUE len)
{
return rb_str_new((char *)NUM2PTR(address), NUM2ULONG(len));
}

/*
* call-seq:
* Fiddle::Pointer.write(address, str)
*
* Write bytes in +str+ to the location pointed to by +address+.
*/
static VALUE
rb_fiddle_ptr_write_mem(VALUE klass, VALUE addr, VALUE str)
{
memcpy(NUM2PTR(addr), StringValuePtr(str), RSTRING_LEN(str));
return str;
}

void
Init_fiddle_pointer(void)
{
Expand All @@ -815,6 +842,8 @@ Init_fiddle_pointer(void)
rb_define_singleton_method(rb_cPointer, "malloc", rb_fiddle_ptr_s_malloc, -1);
rb_define_singleton_method(rb_cPointer, "to_ptr", rb_fiddle_ptr_s_to_ptr, 1);
rb_define_singleton_method(rb_cPointer, "[]", rb_fiddle_ptr_s_to_ptr, 1);
rb_define_singleton_method(rb_cPointer, "read", rb_fiddle_ptr_read_mem, 2);
rb_define_singleton_method(rb_cPointer, "write", rb_fiddle_ptr_write_mem, 2);
rb_define_method(rb_cPointer, "initialize", rb_fiddle_ptr_initialize, -1);
rb_define_method(rb_cPointer, "free=", rb_fiddle_ptr_free_set, 1);
rb_define_method(rb_cPointer, "free", rb_fiddle_ptr_free_get, 0);
Expand Down
16 changes: 16 additions & 0 deletions test/fiddle/test_pointer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,22 @@ def dlwrap arg
Fiddle.dlwrap arg
end

def test_can_read_write_memory
# Allocate some memory
address = Fiddle.malloc(Fiddle::SIZEOF_VOIDP)

bytes_to_write = Fiddle::SIZEOF_VOIDP.times.to_a.pack("C*")

# Write to the memory
Fiddle::Pointer.write(address, bytes_to_write)

# Read the bytes out again
bytes = Fiddle::Pointer.read(address, Fiddle::SIZEOF_VOIDP)
assert_equal bytes_to_write, bytes
ensure
Fiddle.free address
end

def test_cptr_to_int
null = Fiddle::NULL
assert_equal(null.to_i, null.to_int)
Expand Down