使用C#扩展方法从托管C ++ / CLI方法、CLI

2023-09-03 04:48:27 作者:爷、过爷自己的生活

原谅我,如果我的术语是有点过。我的托管C ++ / CLI的知识是非常有限的。

我有一个使用一个dll启用了/ CLR选项MFC应用程序。该DLL使用几个C#的DLL使用WCF的服务器进行通信。在大多数情况下能正常工作。

在C#中的DLL中的一个,我已经添加一个扩展方法的System.Net.IPAddress类,将检索的ip地址目标子网掩码(使用UnicastIPAddressInformation类及其IPv4Mask)。扩展方法的伟大工程,在C#的一面,但我想不出如何使用它在托管C ++ / CLI code。

首先,这甚至可能吗?如果是这样,是什么语法看起来像在托管C ++ / CLI的一面呢?我一定要使用/ CLR:纯选项这个工作

下面是扩展方法的一个例子:

 使用System.Net;
使用System.Net.NetworkInformation;
公共静态类IPAddressExtensions
{
    公共静态ip地址GetSubnetMask(这个ip地址地址)
    {
        UnicastIPAddressInformation AddressInfo的= address.GetAddressInformation(); //省略
        返回((AddressInfo的= NULL)addressInfo.IPv4Mask:!?NULL);
    }
}
 
Unity3D手游开发实践

在我的托管C ++ code,我将如何使用这个扩展方法,如果它甚至有可能?

 无符号长字节= 0x010000FF; //例如地址 -  127.0.0.1
ip地址^地址= gcnew ip地址(BitConverter ::的GetBytes(字节));
ip地址^子网=寻址> GetSubnetMask(); //我如何做到这一点???
 

解决方案

您必须只需要调用它像一个静态方法:

  IPAddressExtensions :: GetSubnetMask(地址);
 

在扩展名的方法更是一个编译器的技巧比CLR的差异。

Forgive me if my terminology is a little off. My knowledge of managed C++/CLI is very limited.

I have an MFC application that uses a dll with the /clr option enabled. This dll uses a couple of C# dlls to communicate with a server using 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). The extension method works great on the C# side, but I cannot figure out how to use it in the managed C++/CLI code.

First, is this even possible? If so, what does the syntax look like on the managed C++/CLI side? Do I have to be using the /clr:pure option for this to work?

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?

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.