C# 奇怪的方法调用使用指针?

标签 c# pointers com

我找到了执行 directx com 导入的代码。但我不明白它,它在我的代码中也不起作用。

就是这段代码:

internal unsafe Result GetCapabilities(out BufferCapabilities dSBufferCapsRef)
{
    BufferCapabilities.__Native native = BufferCapabilities.__NewNative();
    Result result = (Result) **(((IntPtr*) base._nativePointer))[(int) (((IntPtr) 3) * sizeof(void*))](base._nativePointer, (IntPtr) &native);
    dSBufferCapsRef = new BufferCapabilities();
    dSBufferCapsRef.__MarshalFrom(ref native);
    result.CheckError();
    return result;
}

奇怪的是方法中的第二行。结果 结果 = .... _nativePointer 声明如下:

protected unsafe void* _nativePointer;

所以我的回答是如何调用指针所指的 cominterface 的成员。我怎么调用它:(base._nativePointer, (IntPtr) &native)。 它是指针 _nativePointer 指向的接口(interface)的成员。

我知道我有点困惑,但我希望你能理解我的问题。

最佳答案

来自 MSDN - Pointer Types (C# Programming Guide :

* Performs pointer indirection.

-> Accesses a member of a struct through a pointer.

您可以按如下方式使用它们:

指针->字段 或者 (*pointer).field

注意:(同样来自 MSDN - Pointer Types (C# Programming Guide ):

You cannot apply the indirection operator to a pointer of type void*. However, you can use a cast to convert a void pointer to any other pointer type, and vice versa.

看起来有一条主线造成了困惑。我会尝试将其分解:

Result result = (Result) **(((IntPtr*) base._nativePointer))[(int) (((IntPtr) 3) * sizeof(void*))](base._nativePointer, (IntPtr) &native);

第一部分是不言自明的:Result result = (Result)...

然后我们有 **(((IntPtr*) base._nativePointer)),这似乎是将 base._nativePointer 转换为 IntPtr*,然后将其取消引用两次。这意味着它必须指向另一个指针。我们取消引用一次以获得指向的指针,然后再次取消引用以获得该指针的值。我们将其称为 X

下一部分是 [(int) (((IntPtr) 3) * sizeof(void*))]。它获取 void 指针的大小,然后将其乘以 3(不要问我为什么首先将其转换为 IntPtr)。然后它使用该值对 X 进行索引。它正在查找 X 的索引,该索引从一开始就是 3 个 void*。

最后一部分是(base._nativePointer, (IntPtr) &native)。这告诉我 X[3 void's] 的值(上面的伪代码)是一个函数,我们正在调用它。

总的来说,这行代码调用了一个存储在(或附近?)base._nativePointer 指向的指针中的函数。该函数传递参数 base._nativePointer&native(转换为 IntPtr),并返回一个 Result

关于C# 奇怪的方法调用使用指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11125869/

相关文章:

c - 为什么我的指针被锁定在一个范围内?

c++ - 动态分配的数组和堆损坏

c# - COM 方法、Char 类型和 CharSet

c - 运行时检查失败 #0

c++ - 如何更新正在使用的 COM DLL?

c# - ASP.NET - Window.Open(URL) - 文件被缓存,如何停止?

c# - 如果数据模板中的文本框获得焦点,则自动选择 TreeViewItem(不使用代码)

c - "expected specifier-qualifier-list before ‘*’ token “可变参数函数中的错误

c# - 是否有理由以这种方式进行类型比较?

c# - 具有基于任务的异步模式的 UDP 监听器