【问题标题】:sizeof Cannot take the size of a variable of a managed typesizeof 无法获取托管类型变量的大小
【发布时间】:2017-01-26 19:11:33
【问题描述】:

我正在尝试为某些硬件使用一些示例代码,MicroGate controller card。他们提供了一些示例代码,我在使用 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 吗?任何有关如何修复它的建议?我无法想象他们会提供此代码示例并且不希望它工作。任何帮助将不胜感激。

【问题讨论】:

  • sizeof (reference) 只能采用某些类型。 MGSL_PORT 是否总是相同的大小?是可以编辑的类型吗?
  • 是MicroGate提供的API中定义的结构体。
  • 托管类和不可位表结构的大小无效。您正在调用非托管函数,因此您必须提供非托管大小。使用 Marshal.SizeOf()。顺便说一句,这不是你可以从这样的问题中省略的细节。
  • 对不起,我对这个有点不适应。
  • 您不应编辑问题的答案。如果您有答案(并且不是其他人发布的),您应该将其发布为作为答案。然后(经过适当的延迟),您应该接受适合您的答案。这就是我们知道您的问题已成功解决的方式。

标签: c# api hardware-programming


【解决方案1】:

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

rc = MgslEnumeratePorts(ports, (uint) (count * Marshal.SizeOf(typeof(SerialApi.MGSL_PORT))), out count);

【讨论】:

    【解决方案2】:

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

    const int MGSL_SIZE = 37;
    rc = MgslEnumeratePorts(ports, (uint)(count * MGSL_SIZE)), out count);
    

    【讨论】:

    • 对于非结构,您可以使用Marshall. SizeOf () 方法,该方法适用于某些类型,您可以创建一个GCHandle 将对象固定在内存中,然后计算它的大小。
    • @m.rogalski 你的建议让我尝试了: rc = MgslEnumeratePorts(ports, (uint) (count * Marshal.SizeOf(typeof(SerialApi.MGSL_PORT))), out count);如果您提出您的建议作为答案,我会投赞成票。
    • @BigDevJames 如果这对您有用,那么只需使用“答案:”编辑您的问题,就可以了。如果它不起作用,那么我可以调查一些事情:)
    猜你喜欢
    • 1970-01-01
    • 2011-02-03
    • 2011-12-31
    • 1970-01-01
    • 2022-12-28
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多