gpt4 book ai didi

具有委托(delegate)类型字段的 F# Marshall 结构

转载 作者:行者123 更新时间:2023-12-04 15:42:32 24 4
gpt4 key购买 nike

我有一个本地 C 库,我想用它做一些 F# 编码。问题是我得到了异常(exception):

System.TypeLoadException: Cannot marshal field 'log' of type 'LoggingModel': There is no marshaling support for this type.
at System.StubHelpers.ValueClassMarshaler.ConvertToNative(IntPtr dst, IntPtr src, IntPtr pMT, CleanupWorkList& pCleanupWorkList)
at FSI_0009.Initialize(ComponentOverrideFlags flags, LoggingModel& loggingModel, ThreadingModel& threadingModel, SchedulingModel& schedulingModel, IntPtr memoryModel)
at .$FSI_0011.main@() in D:\dev_p\f#\FunBindings\FunExample\Environment.fs:line 16 Stopped due to error



这里的代码:
module Interop

[<CLSCompliant(true); Flags>]
type LogTarget =
| None = 0
| Console = 1
| Trace = 2
| Custom = 4

[<UnmanagedFunctionPointer(CallingConvention.Cdecl)>]
type LogCallback = delegate of LogTarget * string * string * nativeint -> unit

[<UnmanagedFunctionPointer(CallingConvention.Cdecl)>]
type ReleaseCallback = delegate of nativeint -> unit

[<Struct>]
type LoggingModel =
val mutable targets : LogTarget
val mutable log : LogCallback
val mutable deleteModel : ReleaseCallback
val mutable userparam : IntPtr

[<DllImport("CLIBRARY.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "txInitialize")>]
[<MethodImpl(MethodImplOptions.ForwardRef)>]
extern int Initialize(ComponentOverrideFlags flags, LoggingModel& loggingModel, ThreadingModel& threadingModel, SchedulingModel& schedulingModel, IntPtr memoryModel)

module Environment

let initialize =
let mutable loggingModel = new LoggingModel()
let mutable threadingModel = new ThreadingModel()
let mutable schedulingModel = new SchedulingModel()
Initialize(ComponentOverrideFlags.None, &loggingModel, &threadingModel, &schedulingModel, IntPtr.Zero)

基本上,当我尝试以交互方式执行“初始化”功能时,我得到了上述错误。

我真的很感激任何帮助。

更新:我已经检查了更多代码,并注意到在交互式控制台之外它似乎正在工作,没有异常失败。为了确定,我需要为 CLibrary 提供更多的报道。同时,如果有人知道什么可能导致此异常以及如何防止此异常,我将非常感谢您的回答。

最佳答案

我认为问题在于 delegate of LogTarget * string * string * nativeint -> unit声明一个委托(delegate),其中参数被 curry 。 (这对我来说也没有什么意义,因为 a * b 通常代表一个元组。)

微妙的不同delegate of (LogTarget * string * string * nativeint) -> unit声明一个带有元组参数的委托(delegate),该委托(delegate)与 native 函数兼容。

如果您尝试将 .NET 方法分配给两种不同的委托(delegate)类型,您会看到这种差异:

type Curried = delegate of int * int -> int
type Tupled = delegate of (int * int) -> int

//let a = new Curried (Math.Max) // doesn't compile
let b = new Tupled (Math.Max) // works

关于具有委托(delegate)类型字段的 F# Marshall 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32267773/

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