Skip to content

Fix CStruct#clone #67

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
41 changes: 31 additions & 10 deletions lib/fiddle/struct.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,24 @@ class CStruct
include Enumerable

# accessor to Fiddle::CStructEntity
def CStruct.entity_class
def self.entity_class
CStructEntity
end

def self.malloc(func=nil, &block)
if block
entity_class.malloc(types, func, size) do |entity|
block.call(new(entity))
end
else
new(entity_class.malloc(types, func, size))
end
end

def initialize_copy(other)
@entity = other.to_ptr.dup
end

def each
return enum_for(__function__) unless block_given?

Expand Down Expand Up @@ -75,6 +89,16 @@ class CUnion
def CUnion.entity_class
CUnionEntity
end

def self.malloc(func=nil, &block)
if block
entity_class.malloc(types, func, size) do |entity|
block.call(new(entity))
end
else
new(entity_class.malloc(types, func, size))
end
end
end

# Wrapper for arrays within a struct
Expand Down Expand Up @@ -183,15 +207,6 @@ def create(klass, types, members)
size = entity_class.size(types)
define_singleton_method(:alignment) { alignment }
define_singleton_method(:size) { size }
define_singleton_method(:malloc) do |func=nil, &block|
if block
entity_class.malloc(types, func, size) do |entity|
block.call(new(entity))
end
else
new(entity_class.malloc(types, func, size))
end
end
}
return new_class
end
Expand Down Expand Up @@ -274,6 +289,12 @@ def initialize(addr, types, func = nil)
super(addr, @size, func)
end

# Initialize the memory for a struct and copy members from +other+.
def initialize_copy(other)
# TODO
super
end

# Set the names of the +members+ in this C struct
def assign_names(members)
@members = []
Expand Down
20 changes: 20 additions & 0 deletions test/fiddle/test_cstruct.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# frozen_string_literal: true
begin
require_relative 'helper'
rescue LoadError
end

module Fiddle
class TestStruct < TestCase
# https://github.com/ruby/fiddle/issues/66
def test_clone_gh_66
s = Fiddle::Importer.struct(["int i"])
a = s.malloc
a.i = 10
b = a.clone
b.i = 20
assert_equal({a: 10, b: 20},
{a: a.i, b: b.i})
end
end
end