简体   繁体   English

使用托管C ++ / CLI中的C#扩展方法

[英]Using C# extension methods from managed C++/CLI

Forgive me if my terminology is a little off. 如果我的术语有点偏离,请原谅我。 My knowledge of managed C++/CLI is very limited. 我对托管C ++ / CLI的了解非常有限。

I have an MFC application that uses a dll with the /clr option enabled. 我有一个MFC应用程序使用启用了/ clr选项的DLL。 This dll uses a couple of C# dlls to communicate with a server using WCF. 这个dll使用几个C#dll与使用WCF的服务器通信。 For the most part this works fine. 在大多数情况下,这工作正常。

In one of the C# dlls, I've added an extension method to the System.Net.IPAddress class that will retrieve the subnet mask for the IPAddress object (using the UnicastIPAddressInformation class and its IPv4Mask). 在其中一个C#dll中,我向System.Net.IPAddress类添加了一个扩展方法,该方法将检索IPAddress对象的子网掩码(使用UnicastIPAddressInformation类及其IPv4Mask)。 The extension method works great on the C# side, but I cannot figure out how to use it in the managed C++/CLI code. 扩展方法在C#方面运行良好,但我无法弄清楚如何在托管C ++ / CLI代码中使用它。

First, is this even possible? 首先,这甚至可能吗? If so, what does the syntax look like on the managed C++/CLI side? 如果是这样,托管C ++ / CLI端的语法是什么样的? Do I have to be using the /clr:pure option for this to work? 我必须使用/ clr:pure选项才能使用吗?

Here's an example of the extension method: 以下是扩展方法的示例:

using System.Net;
using System.Net.NetworkInformation;
public static class IPAddressExtensions
{
    public static IPAddress GetSubnetMask(this IPAddress address)
    {
        UnicastIPAddressInformation addressInfo = address.GetAddressInformation(); // elided
        return ((addressInfo != null) ? addressInfo.IPv4Mask : null);
    }
}

In my managed C++ code, how would I use this extension method, if it's even possible? 在我的托管C ++代码中,如果可能的话,我将如何使用此扩展方法?

unsigned long bytes= 0x010000FF; // example address - 127.0.0.1
IPAddress^ address = gcnew IPAddress(BitConverter::GetBytes(bytes));
IPAddress^ subnet = address->GetSubnetMask(); // how do I do this???

You have to just call it like a static method: 你必须像静态方法一样调用它:

IPAddressExtensions::GetSubnetMask(address);

The "extension" method is more of a compiler trick than a difference in the CLR. “扩展”方法更多的是编译器技巧,而不是CLR中的差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM