Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
除了比较C#中的非托管函数指针(如何修复CS8909),还有哪些替代方法?_C# - Fatal编程技术网

除了比较C#中的非托管函数指针(如何修复CS8909),还有哪些替代方法?

除了比较C#中的非托管函数指针(如何修复CS8909),还有哪些替代方法?,c#,C#,C#9引入了非托管函数指针(例如,delegate*unmanaged[Cdecl])。我一直在尝试这些,以了解它们是如何工作的。升级到.NET 5.0.201后,我收到一条新警告: error CS8909: Comparison of function pointers might yield an unexpected result, since pointers to the same function may be distinct. 根据,多次引用托管函数可能并不总是产生相同的指针

C#9引入了非托管函数指针(例如,
delegate*unmanaged[Cdecl]
)。我一直在尝试这些,以了解它们是如何工作的。升级到.NET 5.0.201后,我收到一条新警告:

error CS8909: Comparison of function pointers might yield an unexpected result, since pointers to the same function may be distinct.
根据,多次引用托管函数可能并不总是产生相同的指针

以下是可能触发此警告的代码类型的示例:

// saves a function pointer in unmanaged code
[DllImport("mylib", CallingConvention = CallingConvention.Cdecl)]
static extern void set_func(delegate* unmanaged[Cdecl]<void> func);

// retrieves the function pointer that was saved above
[DllImport("mylib", CallingConvention = CallingConvention.Cdecl)]
static extern delegate* unmanaged[Cdecl]<void> get_func();

// unmanaged function implemented in C#
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
static void MyFunc() {
    ...
}

void Test() {
    // pass our unmanaged callers only function to unmanaged code
    set_func(&MyFunc);

    ...

    // sometime later we want to check if unmanaged code still has the same function
    // pointer or if it changed
    if (get_func() == (delegate* unmanaged[Cdecl]<void>)&MyFunc) { // this line triggers CS8909 warning
        ...
    }
}
是否有其他方法可以避免禁用警告

// identical code from above is omitted for brevity, only Test() method is changed

static readonly delegate* unmanaged[Cdecl]<void> myFunc = &MyFunc;

void Test() {
    // pass our unmanaged callers only function to unmanaged code
    set_func(myFunc);

    ...

    // sometime later we want to check if unmanaged code still has the same function
    // pointer or if it changed
#pragma warning disable CS8909
    if (get_func() == myFunc) { // would still trigger warning CS8909 if it was enabled
#pragma warning restore CS8909
        ...
    }