Using UnSafe code to make a pointer move to the next element for a custom class

StackOverflow https://stackoverflow.com/questions/21334794

  •  02-10-2022
  •  | 
  •  

Pergunta

Is it possible to do something like the following in C#?

unsafe string GetName()
{
    Foo[] foo = new Foo[2]; // Create an array of Foo and add two Foo elements
    foo[0] = new Foo { Name = "Bob" };
    foo[1] = new Foo { Name = "Jane" };

    Foo *ptr = &foo;    // Get address of the first element in the array
    ptr++;  // Move to the next element in the array

    return *ptr.Name;  // Expect Name to be "Jane"
}

I'm playing around with custom data structures, and I would like to be able to do this.

I know you can do it with int types etc, but what about user defined structs and classes?

Foi útil?

Solução

You can do this, but only if Foo is a struct where all the fields are "unmanaged types". int is an unmanaged type; string is not. You should use the fixed statement to fix the array in place so that the garbage collector does not move it. Consult chapter 18 of the specification, and note that when you turn the safety system off, it is off. That means that you are responsible for understanding everything about memory management in C# when you write unsafe code. Do you understand everything about memory management? If the answer is "no" then do what I do: don't write unsafe code. I've been writing C# code for ten years and haven't had to write unsafe code (aside from compiler test cases) yet.

You simply should not do this in the first place. There's no need to use unsafe code. If you want something that acts like a pointer to the middle of an array you can do that in a typesafe manner without using pointers.

Here, I've even written the code for you:

http://blogs.msdn.com/b/ericlippert/archive/2011/03/10/references-and-pointers-part-two.aspx

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top