You are quite right!
Changing `immutable` to `type` fixed the problem:

type SmartPointer{T}
    pointer::Ptr{T}

    function SmartPointer(p::Ptr{T})
        smart_p = new(p)
        finalizer(smart_p, p -> c_free(p.pointer))
        smart_p
    end
end 

This seems to work perfectly, prevents the memory leak in my sample code.
Thanks a lot!


On Sunday, March 16, 2014 12:52:00 AM UTC+9, Jameson wrote:
>
> The Julia GC doesn't track immutable types, so it can't finalize them. You 
> must use a regular type if you want it to be tracked by the GC.
>
>
> On Sat, Mar 15, 2014 at 3:44 PM, Kenta Sato <[email protected]<javascript:>
> > wrote:
>
>> Thanks for your reply.
>>
>> I didn't know finalizer(), and that seemed just to be the thing I wanted.
>> Sadly, I couldn't use it for freeing a pointer:
>>
>> julia> finalizer(c_malloc(1024), c_free)
>> ERROR: objects of type Ptr{None} cannot be finalized
>>
>>
>> And this also wouldn't work:
>>
>> immutable SmartPointer{T}
>>     pointer::Ptr{T}
>>
>>     function SmartPointer(p::Ptr{T})
>>         smart_p = new(p)
>>         finalizer(smart_p, p -> c_free(p.pointer))
>>     end
>> end
>>
>> p = SmartPointer{Uint8}(convert(Ptr{Uint8}, c_malloc(1024)))
>>
>> Am I doing something wrong?
>>
>>
>> On Sunday, March 16, 2014 12:12:31 AM UTC+9, Patrick O'Leary wrote:
>>>
>>> Maybe finalizer() will do what you need? http://julia.readthedocs.org/
>>> en/latest/stdlib/base/#Base.finalizer
>>>
>>> On Saturday, March 15, 2014 9:49:56 AM UTC-5, Kenta Sato wrote:
>>>>
>>>> Hi everyone,
>>>>
>>>>  I'm wondering if there are "smart pointers" like C++ in Julia.
>>>> Calling C functions often require managing raw pointers allocated in 
>>>> the C functions.
>>>> After allocating a pointer, I want to wrap it up with a smart pointer, 
>>>> which automatically frees the raw pointer when the smart pointer itself is 
>>>> removed with a garbage collector.
>>>> As for pointers to an array, the `pointer_to_array` method seems to be 
>>>> suitable in this case (http://docs.julialang.org/en/
>>>> latest/stdlib/base/#Base.pointer_to_array).
>>>>
>>>> More generally speaking, I want a functionality that is something like 
>>>> a destructor to manage resources more readily.
>>>> Is it possible to call a function just before a Julia object is 
>>>> destructed?
>>>>
>>>> Thanks.
>>>>
>>>
>

Reply via email to