开发者

How do we access the value pointed by a C pointer in C#?

开发者 https://www.devze.com 2023-03-22 03:03 出处:网络
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 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,

Unmanaged function in C:

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;
}
0

精彩评论

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