我正在使用访问控制设备(终端)。 API 是原生的。 为了将数据发送到设备,我实例化结构(由 API 提供),使用 [Marshal.StructureToPtr] 将其更改为 IntPtr,然后将该指针传递给 API 函数。 这是我正在使用的结构。
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct NameOfTheStruct
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
ushort[] event;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
ushort[] someName;
};
问题是给定结构中的成员名称与 [event] 关键字重叠。如果我更改成员名称,我猜对 native api 的函数调用将失败。
这会不会:
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
[ComAliasName("event")]
ushort[] eventName;
解决我的问题?或者还有其他解决方案吗?
最佳答案
可以使用@
来使用关键字作为标识符:
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
ushort[] @event;
在 C# 中,您可以像这样访问该字段:
yourInstance.@event
不过,@
实际上并不是标识符的一部分。
您可以在“2.4.2 标识符”下的 C# 规范中查找它:
The prefix “@” enables the use of keywords as identifiers, which is useful when interfacing with other programming languages. The character @ is not actually part of the identifier, so the identifier might be seen in other languages as a normal identifier, without the prefix. An identifier with an @ prefix is called a verbatim identifier. Use of the @ prefix for identifiers that are not keywords is permitted, but strongly discouraged as a matter of style.
关于c# - 互操作:结构成员名称与 c# 关键字冲突 - 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15677034/