Keep getting corrupt memory in receivemessages (C# Managed code)

i keep getting error “System.AccessViolationException: ‘Attempted to read or write protected memory. This is often an indication that other memory is corrupt.’”
inn simconnect.ReceiveMessage();

Looking around at google it’s often related to simconnect.dispose(); but i do not have that related to my issue. Got some tips and tricks?

I don’t know what todo, i can easly use fsuipc but cannot for the life of me find a way around this?

Here is my code:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.FlightSimulator.SimConnect;

namespace Simconnect_console_test
{
    internal class Connect
    {
        SimConnect simconnect = null;
        const int WM_USER_SIMCONNECT = 0x0402;
        Stopwatch stopwatch = new Stopwatch();


        public Simvars_structure SimVars_struct_variable;
        public enum DEFINITIONS { Simvars_structure, pftest }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
        public struct Simvars_structure
        {
            public String Title;
            public double Latitude;
            public double Longitude;
            public double Altitude;
        };

        public void Connectsim()
        {
            try
            {
                simconnect = new SimConnect("utracker", Process.GetCurrentProcess().Handle, WM_USER_SIMCONNECT, null, 0);
                simconnect.OnRecvOpen += new SimConnect.RecvOpenEventHandler(Simconnect_OnRecvOpen);

                while (true)
                {
                    Task.Delay(1000).Wait();
                    simconnect.ReceiveMessage();
                }

            }
            catch (COMException e)
            {
                Debug.WriteLine($"Error: {e.Message}");
            }
        }

        private void Simconnect_OnRecvOpen(SimConnect sender, SIMCONNECT_RECV_OPEN data)
        {
            // Define the data structure to be received from simconnect (Simvars)
            simconnect.AddToDataDefinition(DEFINITIONS.pftest, "Title", null, SIMCONNECT_DATATYPE.STRING256, 0.0f, SimConnect.SIMCONNECT_UNUSED);
            simconnect.AddToDataDefinition(DEFINITIONS.pftest, "Plane Latitude", "degrees", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
            simconnect.AddToDataDefinition(DEFINITIONS.pftest, "Plane Longitude", "degrees", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
            simconnect.AddToDataDefinition(DEFINITIONS.pftest, "Plane Altitude", "feet", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);

            // Register the data structure to be received from simconnect
            simconnect.RegisterDataDefineStruct<Simvars_structure>(DEFINITIONS.pftest);
            simconnect.RequestDataOnSimObject(DEFINITIONS.pftest, DEFINITIONS.pftest, SimConnect.SIMCONNECT_OBJECT_ID_USER, SIMCONNECT_PERIOD.SIM_FRAME, SIMCONNECT_DATA_REQUEST_FLAG.DEFAULT, 0, 0, 0);

            // Events
            simconnect.OnRecvSimobjectData += new SimConnect.RecvSimobjectDataEventHandler(Simconnect_OnRecvSimobjectData);
        }

        //called whenever we receive a new set of SimVar data
        private void Simconnect_OnRecvSimobjectData(SimConnect sender, SIMCONNECT_RECV_SIMOBJECT_DATA data)
        {
            SimVars_struct_variable = (Simvars_structure)data.dwData[0];
            Console.WriteLine($"Received: Altitude: {SimVars_struct_variable.Altitude}, Barometer: {SimVars_struct_variable.Title}");
        }
    }
}

You need to specify a fixed size for the String type in your data definition.

   [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
   public String Title;

The SizeConst value must match the DATATYPE size you’re specifying in
AddToDataDefinition(DEFINITIONS.pftest, "Title", null, SIMCONNECT_DATATYPE.STRING256, ...);

See (or check again :slight_smile: ) the example at (5th code block down) https://docs.flightsimulator.com/html/Programming_Tools/SimConnect/Programming_SimConnect_Clients_using_Managed_Code.htm#notes-on-net-client-programming

There’s also no need to pass the Process.GetCurrentProcess().Handle handle to SimConnect c’tor since you’re not using it for message handling (just give it a null instead). For efficient message handling in an actual console app (no Window) you’d want to use a separate wait handle anyway (4th argument in c’tor).

HTH,
-Max

2 Likes