What is the equivalent of Delphi “ZeroMemory” in C#?

北战南征 提交于 2019-12-12 04:58:49

问题


In delphi the "ZeroMemory" procedure, ask for 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!


回答1:


.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.




回答2:


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.




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/5350132/what-is-the-equivalent-of-delphi-zeromemory-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!