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

发布于 2024-08-03 05:23:24 字数 1037 浏览 2 评论 0原文

如果我的术语有点偏差,请原谅我。我对托管 C++/CLI 的了解非常有限。

我有一个 MFC 应用程序,它使用启用了 /clr 选项的 dll。该 dll 使用几个 C# dll 通过 WCF 与服务器进行通信。在大多数情况下,这工作得很好。

在其中一个 C# dll 中,我向 System.Net.IPAddress 类添加了一个扩展方法,该方法将检索 IPAddress 对象的子网掩码(使用 UnicastIPAddressInformation 类及其 IPv4Mask)。扩展方法在 C# 方面效果很好,但我不知道如何在托管 C++/CLI 代码中使用它。

首先,这可能吗?如果是这样,托管 C++/CLI 端的语法是什么样的?我是否必须使用 /clr:pure 选项才能正常工作?

下面是扩展方法的示例:

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);
    }
}

在我的托管 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???

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???

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

因为看清所以看轻 2024-08-10 05:23:24

您必须像静态方法一样调用它:

IPAddressExtensions::GetSubnetMask(address);

“扩展”方法更多的是编译器技巧,而不是 CLR 中的差异。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文