I've tried passing perl pointers to Cocoa methods using the
PerlObjCBridge. I can't get it to work, probably because Perl
pointers "don't let you peek and poke at raw memory locations" (Adv
Perl Programming). Does anyone know of a way to get this to work?
For example, I'm trying to pass an int by reference:
#!/usr/bin/perl
use Foundation;
my $value;
$rawdata = NSString->stringWithFormat_("12358D");
$scanner = NSScanner->scannerWithString_( $rawdata );
$scanner->scanHexInt_( \$value );
print $value;
Nothing prints. Here is the Cocoa code, which works.
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int val;
NSString *rawdata = [NSString stringWithFormat:@"12358D"];
NSScanner *scanner = [NSScanner scannerWithString:rawdata];
[scanner scanHexInt:&val];
NSLog (@"%d", val);
[pool release];
return 0;
}
Another example is this, which tries to pass a pointer to raw bytes.
However, I may not have a full understanding of this code, as I don't
really work with raw data much (pack, and dataWithBytes expects a
"const void *"). (I've tried many different forms of the following
code, and I haven't gotten anything to work correctly).
#!/usr/bin/perl
use Foundation;
$bytes = pack ("H*", "12358D" );
$data = NSData->dataWithBytes_length_( \$bytes, length $bytes );
print $data->description->cString();
--
James Reynolds
http://james.magnusviri.com
james@magnusviri.com - james@scl.utah.edu
Sherm Pendley - 05 Jul 2005 07:18 GMT
> I've tried passing perl pointers to Cocoa methods using the
> PerlObjCBridge.
Perl doesn't have pointers, Perl has references. They're
superficially similar, but under the hood they're completely
different beasts.
> For example, I'm trying to pass an int by reference:
... Broken example snipped ...
> Nothing prints. Here is the Cocoa code, which works.
>
[quoted text clipped - 12 lines]
> return 0;
> }
Here's a Perl version that works in both PerlObjCBridge and CamelBones:
#!/usr/bin/perl
use strict;
use warnings;
use Foundation;
# Or, use CamelBones instead... :-)
# use CamelBones qw(:Foundation);
# Allocate enough space to hold a 4-byte int
my $value = "\0" x 4;
# Create a scanner
my $scanner = NSScanner->scannerWithString_('12358D');
# Get a pointer to $value, with pack(). That pointer is returned
# in a 4-byte string scalar, *not* as a numeric value - to
"promote"
# those 4 bytes to a numeric value, we unpack() them:
my $valuePointer = unpack("L", pack("p", $value));
# Scan
$scanner->scanHexInt_($valuePointer);
# Now, use unpack() to interpret the four bytes that were stored in
# $value as an integer
my ($intValue) = unpack("I", $value);
print "Int value: $intValue\n";
sherm--
Cocoa programming in Perl: http://camelbones.sourceforge.net
Hire me! My resume: http://www.dot-app.org