开发者

What is the equivalent of Delphi "ZeroMemory" in C#?

开发者 https://www.devze.com 2023-02-17 10:08 出处:网络
In delphi the \"ZeroMemory\" procedure, ask for 开发者_JAVA百科two parameters. CODE EXAMPLE procedure ZeroMemory(Destination: Pointer; Length: DWORD);

In delphi the "ZeroMemory" procedure, ask for 开发者_JAVA百科two parameters.

CODE EXAMPLE

procedure ZeroMemory(Destination: Pointer; Length: DWORD);
begin
 FillChar(Destination^, Length, 0);
end;

I want make this, or similar in C#... so, what's their equivalent?

thanks in advance!


.NET framework objects are always initialized to a known state

.NET framework value types are automatically 'zeroed' -- which means that the framework guarantees that it is initialized into its natural default value before it returns it to you for use. Things that are made up of value types (e.g. arrays, structs, objects) have their fields similarly initialized.

In general, in .NET all managed objects are initialized to default, and there is never a case when the contents of an object is unpredictable (because it contains data that just happens to be in that particular memory location) as in other unmanaged environments.

Answer: you don't need to do this, as .NET will automatically "zero" the object for you. However, you should know what the default value for each value type is. For example, the default of a bool is false, and the default of an int is zero.

Unmanaged objects

"Zero-ing" a region of memory is usually only necessary in interoping with external, non-managed libraries.

If you have a pinned pointer to a region of memory containing data that you intend to pass to an outside non-managed library (written in C, say), and you want to zero that section of memory, then your pointer most likely points to a byte array and you can use a simple for-loop to zero it.

Off-topic note

On the flip side, if a large object is allocated in .NET, try to reuse it instead of throwing it away and allocating a new one. That's because any new object is automatically "zeroed" by the .NET framework, and for large objects this clearing will cause a hidden performance hit.


You very rarely need unsafe code in C#. Usually only when interacting with native libraries.

The Marshal class as some low level helper functions, but I'm not aware of any that zeros out memory.


Firstly, in .Net (including C#) then value types are zero by default - so this takes away one of the common uses of ZeroMemory.

Secondly, if you want to zero a list of type T then try a method like:

void ZeroMemory<T>(IList<T> destination)
{
    for (var i=0;i<destination.Count; i+))
   {
       destination[i] = default(T);
   }
}

If a list isn't available... then I think I'd need to see more of the calling code.


Technically there is the Array.Clear, but it's only for managed arrays. What do you want to do?

0

精彩评论

暂无评论...
验证码 换一张
取 消