ImageSharp icon indicating copy to clipboard operation
ImageSharp copied to clipboard

Add memory size to WrapMemory(void* ...);

Open vpenades opened this issue 5 years ago • 2 comments

Prerequisites

  • [x] I have written a descriptive issue title
  • [x] I have verified that I am running the latest version of ImageSharp
  • [x] I have verified if the problem exist in both DEBUG and RELEASE mode
  • [x] I have searched open and closed issues to ensure it has not already been reported

Description

I've noticed the new WrapMemory method allowing to initialize an image with a raw, low level pointer, which is great.

I would suggest to add a memory length argument, so the method would look like this:

WrapMemory<TPixel>(
            void* pointer,
            int byteLength, // byte length of the memory allocated
            int width,
            int height)

It might look redundant, since the underlaying code does know which is the expected memory size, and the caller is responsible to allocate that amount of memory.

But in practice, we do know that things are not that easy, and in the worst case scenario it can happen that a developer might misunderstand or code an incorrect implementation that allocates less memory than required, and by sheer luck, it doesn't crash and might seem the code is right.

Given that in general, anybody allocating low level memory does know the amount of allocated memory, and most APIs I've seen that provide pointers, also provide the memory length in bytes, it seems reasonable that the WrapMemory method checks both the pointer not being null, and the memory length being enough to meet the Image needs.

So in essence, this argument is only used as an extra safety check, and given the dangerous nature of unmanaged code, it would be very useful to detect errors early.

Steps to Reproduce

System Configuration

  • ImageSharp version: 1.0.2
  • Other ImageSharp packages and versions: -
  • Environment (Operating system, version and so on): all
  • .NET Framework version: all
  • Additional information:

vpenades avatar Dec 31 '20 16:12 vpenades

Makes sense to me. @Sergio0694 thoughts?

antonfirsov avatar Jan 02 '21 00:01 antonfirsov

Let's move this to a discussion where it belongs.

JimBobSquarePants avatar Jan 02 '21 02:01 JimBobSquarePants

Closed via #2313

JimBobSquarePants avatar Jan 22 '23 13:01 JimBobSquarePants