How do we access the value pointed by a C pointer in C#?
In my C# application I have IntPtr y = VoidPointer(x);
where VoidPointer(x) is an unmanaged function that returns a void*(void pointer). The problem is I am not getting the correct value pointed by y in the C# code. I am using Marshal.ReadInt32(y)
and have tried ReadByte
, ReadInt64
etc. Below are the code snippets,
void* VoidPointer()
{
int Var1 = 7113;
return &Var1;
}
Managed function in C# :(using DllImport to access开发者_如何学JAVA the unmanaged function.)
IntPtr z = VoidPointer();
Console.WriteLine(" z = {0} ", Marshal.ReadInt32(z));
But in the output I am not getting 7113. How can I access the correct value of Var1 in C# ?
VoidPointer
returns a pointer to local variable which goes out of scope when the function ends. This is undefined behavior.
Try declaring Var1 as static:
void* VoidPointer()
{
static int Var1 = 7113;
return &Var1;
}
精彩评论