0

我正在尝试为某些硬件使用一些示例代码,即MicroGate 控制器卡。他们提供了一些示例代码,我在使用 sizeof 的行中遇到了错误。这是示例代码:

public static uint GetPortID(string name)
    {
        uint i, rc, count;
        uint port_id = 0;
        MGSL_PORT[] ports;

        /* get count of available ports */
        rc = MgslEnumeratePorts(null, 0, out count);
        if (rc != 0 || count == 0)
            return 0;

        /* allocate memory to hold port information */
        ports = new MGSL_PORT[count];

        /* get port information */
        rc = MgslEnumeratePorts(ports, (uint)(count * sizeof(MGSL_PORT)), out count);
        if (rc != 0 || count == 0)
            return 0;

        /* search for entry with matching name */
        for (i=0; i < count; i++) {
            string port_name;
            char[] port_chars = new char[25];
            uint j;
            fixed (byte* sendBuf = ports[i].DeviceName)
            {
                for (j=0 ; j < 25; j++)
                    port_chars[j] = (char)sendBuf[j];
            }
            port_name = new string(port_chars);
            if (String.Compare(port_name.ToUpper(), name.ToUpper()) == 0) {
                port_id = ports[i].PortID;
                break;
            }
        }
        return port_id;
    }

线上是:

rc = MgslEnumeratePorts(ports, (uint)(count * sizeof(MGSL_PORT)), out count);

Visual Studio 指示“无法获取托管类型 'MGSL_PORT' 的变量的大小。出于好奇,我们是否认为此代码过去可能有效?我是否需要不同版本的 Visual Studio?有关如何操作的任何建议修复它?我无法想象他们会提供这个代码示例并且不希望它工作。任何帮助将不胜感激。

4

2 回答 2

1

我能够通过使用 Marshal.SizeOf 获得结构的大小。我的代码行现在是:

rc = MgslEnumeratePorts(ports, (uint) (count * Marshal.SizeOf(typeof(SerialApi.MGSL_PORT))), out count);
于 2017-05-31T12:04:01.010 回答
0

sizeof参考)只能采取某些类型。从引用中,struct仅当它不包含任何引用类型时才可以采用 a。如果该类型确实具有恒定的已知大小(API 参考),您可以执行以下操作:

const int MGSL_SIZE = 37;
rc = MgslEnumeratePorts(ports, (uint)(count * MGSL_SIZE)), out count);
于 2017-01-26T19:40:30.077 回答