Jump to content

Create an object at a given address: Difference between revisions

Create Perl 6 example
No edit summary
(Create Perl 6 example)
Line 533:
0 1 2 3 4 5 6 7
506097522914230528</pre>
 
=={{header|Perl 6}}==
Perl 6 has fairly comprehensive facilities for accessing allocating and accessing memory and also declaring C-style structs, via the NativeCall interface, as this example demonstrates.
<lang perl6>use v6;
use NativeCall;
use NativeCall::Types;
 
# bind to basic libc memory management
sub malloc(size_t) returns Pointer[uint8] is native {*};
sub memset(Pointer, uint32, size_t) is native {*};
sub free(Pointer[uint8]) is native {*};
 
my Pointer[uint8] $base-p = malloc(100);
memset($base-p, 0, 100);
 
# define object as a C struct that contains a short and an int
class SampleObject is repr('CStruct') {
has uint16 $.foo is rw;
has uint8 $.bar is rw;
}
 
# for arguments sake our object is at byte offset 64 in the
# allocated memory
 
my $offset-p = $base-p.clone.add(64);
my $object-p := nativecast(Pointer[SampleObject], $offset-p);
note "creating object at address {+$object-p}";
 
my $struct := $object-p.deref;
 
$struct.foo = 41;
$struct.bar = 99;
 
# check we can update
$struct.foo++; # 42
 
# run some tests. Try to be archecture indenpdent
 
use Test;
 
# 42 should be in first or second byte, depending on endianess
is ($base-p[64+0] || $base-p[64+1]), 42, 'object first field';
 
# the exact position of the second field may depend on record alignment.
# fair chance it's +2 (unpacked) +4 (32 bit) or +8 (64 bit)
is ($base-p[64+2] || $base-p[64+4] || $base-p[64+8]), 99, 'object second field';
 
# tidy up
free($base-p);
done-testing;
</lang>
{{out}}
<pre>creating object at address 94299589110352
ok 1 - object first field
ok 2 - object second field
1..2
</pre>
=={{header|Phix}}==
Phix does not support creation of a "language object" at a specific address, but you can peek and poke bytes, words, dwords and qwords
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.