【发布时间】: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