c# - 互操作:结构成员名称与 c# 关键字冲突 - 事件

标签 c# .net interop

我正在使用访问控制设备(终端)。 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/

相关文章:

c# - 使用 MongoDB 和 C# 将元素附加到现有项目的数组

c# - 以编程方式将 Doc 转换为 Docx bug

c# - Visual Studio 模板 "Generate Method Stub"

c# - 将信息从我的列表框发送到不同的应用程序文本框

.net - HttpClient.ReadAsAsync<T> 在使用 [Serializable] 时返回空对象

c# - 是否可以读取实习生池中的所有字符串?

c# - 我什么时候应该明确指定一个 StructLayout?

c# - C++/CLI 使用抽象方法从 native C++ 类继承并将其公开给 C#

c# - 无需 Ghostscript 的 PDF 到图像转换器

c# - C#-使用依赖项注入(inject)(ninject)代替工厂模式