指向 F# 中指针的指针

Pointer to a pointer in F#

我目前正在尝试学习 .NET 的 P/Invoke 功能,尤其是在 F# 中。我试图调用的 C 函数需要一个 'pointer to a pointer' 参数,我正在努力寻找在 F# 中使用哪个运算符来表示它。

读了一些书后,尤其是这个 blog post,我开始相信在 .NET 语言中,用 & 表示指针参数比 * 更好] 这样它们就是 'Managed Pointers'(如果有人可以为我澄清任何我 不应该 使用托管指针的用例,那也太好了!)。 因此,到目前为止,我已经尝试了 &&,这是不正确的,因为它代表布尔 AND,而且我还尝试了 **,它会匹配指针的 'C' 样式表示指针。

我相信在 C# 中,您可以用类似于 'C' 样式的方式表示它,即 int** q;

有人知道如何在 F# 中做类似的事情吗?特别是在 extern 定义中。

谢谢。

更新

抱歉没有更具体 - 这是结构类型。

准确地说我在这里做什么 - 我正在尝试复制结构 MMAL_BUFFER_HEADER_T 发现 here for a project I'm working on with the Raspberry Pi Camera Module. This struct is then used in the following function。指针的地址将在函数返回时设置。

更新 2 在这里大声思考 - 使用 System.IntPtr& 会以正确的方式表示吗?

我费了很大力气才正确检查这个,但试试这个。

当然,您必须确保获得正确的类型和源属性。 Sequential 和 Cdecl 是否正确?如果您不需要在 F# 中引用结构的字段,换句话说,将其视为不透明类型,那么您可以在函数头中使用 nativeint(带或不带&符号?)在 C 中使用 void 指针的方式

open System.Runtime.InteropServices

type uint32_t = uint32 // likely correct type, but you must check
type MMAL_STATUS_T = int32 // replace with correct type
type MMAL_PORT_T = int32 // replace with correct type

#nowarn "9"
[<Struct; StructLayout(LayoutKind.Sequential)>]
type MMAL_BUFFER_HEADER_T =
    val next: MMAL_BUFFER_HEADER_T ref // will ref work here, or should it be byref<MMAL_BUFFER_HEADER_T>?
    val priv: nativeint // or you could use a type (with ref?) here also
    val cmd: uint32_t // assuming uint32_t is uint32
    // etc
    val typ: MMAL_BUFFER_HEADER_TYPE_SPECIFIC_T ref
    val user_data: nativeint // void pointer in C

[<DllImport("SomeDll.dll", CallingConvention=CallingConvention.Cdecl)>]
extern MMAL_STATUS_T mmal_port_event_get(MMAL_PORT_T port, MMAL_BUFFER_HEADER_T& buffer, uint32_t event)

为了防止其他人碰巧遇到这个问题,我最终使用 nativeint& 来表示函数调用所需的多重间接寻址。该函数本身会为我分配内存,所以我很乐意继续使用这种方法。再次感谢所有帮助过我的人。