如何将 WinDef.POINT 转换为 WinDef.POINT.ByValue?

How do you convert a WinDef.POINT to a WinDef.POINT.ByValue?

假设我收到 WinDef.POINT 使用 User32.INSTANCE.GetCursorPos。如何将此 WinDef.POINT 传递给需要 WinDef.POINT.ByValue 的函数?

WinDef.POINT.ByValue class 包括一个 Pointer constructor.

您可以使用 Structure class 方法 getPointer().

Pointer 检索到您收到的 POINT 结构

我可能会这样做的一种类型安全的方式:

WinDef.POINT thePoint = new WinDef.POINT();
User32.INSTANCE.GetCursorPos(thePoint);
WinDef.POINT.ByValue thePointByVal = new WinDef.POINT.ByValue(thePoint.getPointer());
passThePointToTheOtherFunction(thePointByVal);

了解 class 的内部工作原理后,我可以看到嵌套的 ByValue class 扩展了 POINT class 而不更改其字段的任何内容, 所以简单的类型转换在这里可以工作,尽管可能被认为是代码味道:

WinDef.POINT thePoint = new WinDef.POINT();
User32.INSTANCE.GetCursorPos(thePoint);
passThePointToTheOtherFunction((WinDef.POINT.ByValue) thePoint);

向上转换也可能“更安全”,但由于我们仍然故意造成不同的行为,它依赖于实现细节,也可能是代码味道:

WinDef.POINT.ByValue thePoint = new WinDef.POINT.ByValue();
// Explicitly upcast to trigger default ByReference behavior
User32.INSTANCE.GetCursorPos((WinDef.POINT) thePoint);
passThePointToTheOtherFunction(thePoint);