Memory address of an integer in C#
I am trying to get the memory address for a low-memory trick from an int pointer in C#. However, when I check the output, it seems to be printing the int's value, not its memory address. Below is my code:
using (XmlWriter writer = XmlWriter.Create(newBuilder))
{
w开发者_运维问答riter.WriteStartDocument();
writer.WriteStartElement("Data");
GCHandle handle = GCHandle.Alloc(Nodes, GCHandleType.Normal);
//fixed(int * p = &Nodes[0].value) {
for (int i = 0; i < Nodes.Count; i++)
{
writer.WriteStartElement("Node");
writer.WriteStartElement("Value");
writer.WriteValue(this.Nodes[i].Value);
writer.WriteEndElement();
fixed (int* name = &Nodes[i].value)
{
writer.WriteStartElement("Name");
writer.WriteValue(name->ToString());
writer.WriteEndElement();
}
if (Nodes[i].Parent1 != null)
{
fixed (int* parent1 = &Nodes[i].Parent1.value)
{
writer.WriteStartElement("Parent1");
writer.WriteValue(parent1->ToString());
writer.WriteEndElement();
}
}
if (Nodes[i].Parent2 != null) {
fixed (int* parent2 = &Nodes[i].Parent2.value)
{
writer.WriteStartElement("Parent2");
writer.WriteValue(parent2->ToString());
writer.WriteEndElement();
}
}
writer.WriteEndElement();
}
//}
handle.Free();
writer.WriteEndElement();
writer.WriteEndDocument();
//XmlSerializer serializer = new XmlSerializer(typeof(List<Node>));
//serializer.Serialize(writer, this.Nodes);
}
Any idea why it's doing that?
Thanks
Your code writes the value of the integer, because you dereference the pointer and invoke the ToString Method on the integer value.
Try ((IntPtr)name).ToString()
. name->ToString()
calls the ToString
method on the int
pointed to by name
.
精彩评论