#BUGFIX by cg
authorClaus Gittinger <cg@exept.de>
Tue, 29 Aug 2017 20:01:57 +0200
changeset 22224 914289d8db20
parent 22223 579090043bea
child 22225 3984da94914f
#BUGFIX by cg EXPERIMENTAL: allocate external memory under control of GC (i.e. extermalBytes will vanish, if unreferenced) class: ExternalBytes class added: #protectedNew: changed: #new:
ExternalBytes.st
--- a/ExternalBytes.st	Tue Aug 29 15:40:00 2017 +0200
+++ b/ExternalBytes.st	Tue Aug 29 20:01:57 2017 +0200
@@ -432,14 +432,11 @@
      may change their address.
 
      DANGER ALERT: the memory is NOT automatically freed until it is either
-		   MANUALLY freed (see #free) or the returned externalBytes object
-		   is unprotected or the classes releaseAllMemory method is called."
+                   MANUALLY freed (see #free) or the returned externalBytes object
+                   is unprotected or the classes releaseAllMemory method is called."
 
-    |newInst|
-
-    newInst := self unprotectedNew:numberOfBytes.
-    newInst protectFromGC.
-    ^ newInst
+    "/ ^ self protectedNew:numberOfBytes.
+    ^ self unprotectedNew:numberOfBytes.
 
     "
      |bytes|
@@ -449,6 +446,8 @@
      bytes doubleWordAt:3 put:16r12345678.
      bytes inspect
     "
+
+    "Modified: / 29-08-2017 / 16:52:31 / cg"
 !
 
 newNullTerminatedFromString:aString
@@ -483,6 +482,40 @@
     "Modified (comment): / 31-03-2016 / 11:05:37 / cg"
 !
 
+protectedNew:numberOfBytes
+    "allocate some memory usable for data;
+     the memory safe from being finalized by the garbage collector.
+     Return a corresponding ExternalBytes object or raise MallocFailure (if malloc fails).
+
+     Use this, if you have to pass a block of bytes to some
+     external destination (such as a C function) which does not copy the
+     data, but instead keeps a reference to it. For example, many functions
+     which expect strings simply keep a ref to the passed string - for those,
+     an ST/X string-pointer is not the right thing to pass, since ST/X objects
+     may change their address.
+
+     DANGER ALERT: the memory is NOT automatically freed until it is either
+                   MANUALLY freed (see #free) or the returned externalBytes object
+                   is unprotected or the classes releaseAllMemory method is called."
+
+    |newInst|
+
+    newInst := self unprotectedNew:numberOfBytes.
+    newInst protectFromGC.
+    ^ newInst
+
+    "
+     |bytes|
+
+     bytes := ExternalBytes new:100.
+     bytes wordAt:1 put:1.
+     bytes doubleWordAt:3 put:16r12345678.
+     bytes inspect
+    "
+
+    "Created: / 29-08-2017 / 16:52:14 / cg"
+!
+
 unprotectedNew:numberOfBytes
     "allocate some memory usable for data;
      the memory is under the control of the garbage collector (i.e. the instance will