[Vm-beginners] Return strings in numeric primitives
David T. Lewis
lewis at mail.msen.com
Sat Jun 30 18:08:21 UTC 2012
On Sat, Jun 30, 2012 at 12:15:01PM -0300, David Leonhardt wrote:
> Hey.
>
> I'm doing my own numeric primitive.
> I could return numeric values, doing something like:
>
> self pop: 1 thenPush: ( objectMemory integerObjectOf: 21
> ).
>
> What I couldn't do is find a way to return a string, for example 'Hello
> World'.
Here is one way to do it. This example is from OSProcessPlugin. If you load
OSProcessPlugin from SqueakSource, you can find a few examples of how this
is used in the primitives.
stringFromCString: aCString
"Answer a new String copied from a null-terminated C string.
Caution: This may invoke the garbage collector."
| len newString p |
<var: 'aCString' type: 'const char *'>
<var: 'p' type: 'void *'>
len := self
cCode: 'strlen(aCString)'
inSmalltalk: [aCString size].
newString := interpreterProxy
instantiateClass: interpreterProxy classString
indexableSize: len.
p := interpreterProxy arrayValueOf: newString.
self cCode: 'strncpy(p, aCString, len)'
inSmalltalk: [ | s |
s := interpreterProxy firstIndexableField: newString.
(1 to: len) do: [:i | s at: i - 1 put: (aCString at: i) asciiValue]].
^ newString
HTH,
Dave
More information about the VM-beginners
mailing list