[Matrix-SIG] Freeing malloc'd array in Python

Zane Motteler zcm@llnl.gov
Tue, 8 Sep 1998 07:55:41 -0800

Hi Scott,

Unlike a lot of workaholics, I took Labor Day off. ;-} So I've
read the correspondence about freeing a malloc'ed array in
Python, by which I understand you to mean that you want Python
to do the freeing when the array's reference count reaches zero.

I hate to expose myself as an unregenerate hacker, but there
is a way to do it (and you'll see it done shamelessly in
gistCmodule.c). The thing is, when you create an array with
PyArray_FromDimsAndData, there is a flag in the struct which
says, in effect, I don't own this data, so don't free it when
my reference count reaches zero. You can fool mother nature
by setting this flag to the opposite setting. Suppose op
is the name of the array you created. Then simply do

op->flags |= OWN_DATA

That makes Python think that *it* owns the data, so when
the reference count reaches zero, it will be freed.

Paul and Konrad are absolutely correct when they say that
PyArray_FromDimsAndData was intended to create either an
array to hold static data, or else one to hold data which you
are responsible for freeing. However, in gistCmodule we
found the above trick indispensable. I agree with you that
it seems wasteful to copy the data if you really don't
have to.

Hope this helps.


                      Zane C. Motteler, Ph. D.
Computer Scientist             | Professor Emeritus of
Lawrence Livermore National    |    Computer Science and Engineering
   Laboratory                  | California Polytechnic
P. O. Box 808, L-038           |    State University
Livermore, CA 94551-0808       | San Luis Obispo, CA 93407
925/423-2143, FAX 925/423-9969 | zmottel@hornet.csc.calpoly.edu
zcm@llnl.gov, motteler@icf.llnl.gov
(For FedEx, UPS, etc. use 7000 East Avenue, zip 94550-9234)