Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
598 views
in Technique[技术] by (71.8m points)

.net - 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.

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???
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...