private void ReadSharedMem_Click(object sender, EventArgs e) { IntPtr ptr; try { ptr = Marshall.AllocHGlobal(Marshall.SizeOf(typeof(SYSTEM_OUTPUT))); int ret = getStatus(ptr); if (ret == 0) { output = (SYSTEM_OUTPUT)Marshal.PtrToStructure(ptr, typeof(SYSTEM_OUTPUT)); } //do something with output label1.Text = ret; } catch (AccessViolationException ave) { label1.Text = ave.Message; } finally { Marshal.FreeHGlobal(ptr); //make sure to free the memory } }