gpt4 book ai didi

f# - 为什么这两个都编译但只有一个运行?

转载 作者:行者123 更新时间:2023-12-01 12:22:26 26 4
gpt4 key购买 nike

open System
open System.Diagnostics
open System.Runtime.InteropServices
module PInvoke =
type EnumThreadDelegate= delegate of (IntPtr * IntPtr) -> bool
type ComArrayList() =
inherit System.Collections.ArrayList()

[<DllImport("user32.dll")>]
extern [<return: MarshalAs(UnmanagedType.Bool)>] bool private EnumThreadWindows(int dwThreadId, EnumThreadDelegate lpfn, IntPtr lParam);
let getThreadWindows (threadId:int) : _ list =
let items = ResizeArray()
let withData (hWnd:IntPtr, lParam:IntPtr) =
let _ = items.Add(hWnd,lParam)
true
let f = EnumThreadDelegate withData

EnumThreadWindows (threadId, f, IntPtr.Zero) |> ignore<bool>
items
|> Seq.cast<IntPtr*IntPtr>
|> List.ofSeq


let lp = Process.GetProcesses() |> Seq.filter(fun p -> p.ProcessName.StartsWith("L")) |> Seq.minBy(fun p -> p.StartTime)
lp.Threads
|> Seq.cast<ProcessThread>
|> Seq.map (fun t -> t.Id)
|> Seq.map PInvoke.getThreadWindows
|> List.ofSeq

给出 System.Runtime.InteropServices.MarshalDirectiveException: Cannot marshal 'parameter #1': Generic types cannot be marshaled

但是这个编译并运行:

open System
open System.Diagnostics
open System.Runtime.InteropServices
module PInvoke =
type EnumThreadDelegate= delegate of IntPtr * IntPtr -> bool
type ComArrayList() =
inherit System.Collections.ArrayList()

[<DllImport("user32.dll")>]
extern [<return: MarshalAs(UnmanagedType.Bool)>] bool private EnumThreadWindows(int dwThreadId, EnumThreadDelegate lpfn, IntPtr lParam);
let getThreadWindows (threadId:int) : _ list =
let items = ResizeArray()
let withData (hWnd:IntPtr) (lParam:IntPtr) =
let _ = items.Add(hWnd,lParam)
true
let f = EnumThreadDelegate withData

EnumThreadWindows (threadId, f, IntPtr.Zero) |> ignore<bool>
items
|> Seq.cast<IntPtr*IntPtr>
|> List.ofSeq


let lp = Process.GetProcesses() |> Seq.filter(fun p -> p.ProcessName.StartsWith("L")) |> Seq.minBy(fun p -> p.StartTime)
lp.Threads
|> Seq.cast<ProcessThread>
|> Seq.map (fun t -> t.Id)
|> Seq.map PInvoke.getThreadWindows
|> List.ofSeq

为什么两个都能编译,一个却给出异常?

delegate of (IntPtr*IntPtr) -> booldelegate of IntPtr*IntPtr->bool 之间有什么区别?他们不应该是同一件事吗? (IntPtr*IntPtr)IntPtr*IntPtr 不同吗?

最佳答案

我觉得

delegate of (IntPtr*IntPtr) -> bool

是一个接受 Tuple<IntPtr,IntPtr> 的单参数委托(delegate), 而

delegate of IntPtr*IntPtr -> bool

是一个双参数委托(delegate),需要两个 IntPtr s 作为它的两个参数。

关于f# - 为什么这两个都编译但只有一个运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42985057/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com