[Insight-users] native function returning an itk::Image

Luis Ibanez luis.ibanez at kitware.com
Sun Aug 31 10:56:45 EDT 2008


Hi Protein,


In order to keep an ITK image alive when returning it from
a function, you *MUST* return it as a SmartPointer.

Instead of your current signature:

      ImageType* readImg(char* imageFileName);

You should use

     ImageType::Pointer readImg(char* imageFileName);


In that way the smart pointer will be copied in the stack when
the function is returning, and that temporary copy wil keep the
image alive long enough to survive the destruction of data in
the local scope of the function.

Make sure that the returned variable is assigned to a
SmartPointer as well.


That is, when you call the function do something like:

    ImageType::Pointer myImage = readImg("brain.dcm");


NOTE: You *do not* need, and you *should not* modify the
       reference counting of ITK images. SmartPointers
       are supposed to do that for you.



   Regards,


       Luis


---------------
protein wrote:
> Hey all,
> 
> This might be a duplicated question but I really didn't find a answer..
> 
> Basically my scenario could be described as to write a native function
> to read a .png file, using an instantiated itk::ImageFileReader<unsigned char>,
> and return an itk::Image<unsigned char>. How to keep that itk::Image alive
> after returning from the native function?
> 
> So in the header file I defined:
> 
>    const    unsigned int    Dimension = 2;
>    typedef  float           PixelType;
>    typedef itk::Image< PixelType, Dimension >  ImageType;
>    typedef itk::ImageFileReader< ImageType  > ImageReaderType;
> 
> then I declear a function, which takes
> char* imageFileName as input
> and
> output an ImageType*
> 
>     ImageType* readImg(char* imageFileName);
> 
> the definition readImg function:
>     ImageReaderType reader = ImageReaderType::New();
>     reader->SetFileName(imageFileName);
>     reader->Update();
>     return reader->GetOutput();
> 
> 
> But when calling this function in main(), by:
>     ImageType::Pointer img = readImg("test.png");
> 
> I know the reader is destructed when going back to main, thus the
> there will be error.
> 
> So I increased the reference count of reader before returning,
> to keep it alive even after returned from the readImg function, I added:
>     reader->SetReferenceCount(1+reader->GetReferenceCount());
> before "return reader->GetOutput();"
> 
> Then in the main, I could use the img.
> 
> However this seems not that nice to me since reader won't get released....
> 
> 
> Could anyone tell me in general how to deal with such kind of problems?
> I really appreciate that!
> 
> Thanks,
> Yi
> _______________________________________________
> Insight-users mailing list
> Insight-users at itk.org
> http://www.itk.org/mailman/listinfo/insight-users
> 


More information about the Insight-users mailing list