在Xamarin.Mac中导入本机方法

问题描述 投票:3回答:3

我正在Xamarin.Mac应用程序中寻找使用SCNetworkInterfaceCopyAll的方法。我已经导入了

[DllImport("/System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration")]
public static extern IntPtr SCNetworkInterfaceCopyAll();

然后我通过调用var array = NSArray.ArrayFromHandle<NSObject>(pointer)得到一个数组。但是无法弄清楚如何从SCNetworkInterface的输出数组获取值。我试图将其封送为

[StructLayout(LayoutKind.Sequential)]
public struct Test
{
    IntPtr interface_type;
    IntPtr entity_hardware;
}

然后调用Marshal.PtrToStructure<Test>(i.Handle),但它给出了随机指针而不是有意义的值。

xamarin interop marshalling dllimport xamarin.mac
3个回答
0
投票

您可以使用System.Net.NetworkInformation. NetworkInterface提供的信息(还是您实际上需要SCNetworkInterface?]

Xamarin.Mac示例:

foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
    if (nic.OperationalStatus == OperationalStatus.Up)
        Console.WriteLine(nic.GetPhysicalAddress());
}

0
投票

查看SCNetworkConfiguration.h,您似乎在IntPtr上调用了许多C API来检索所需的特定信息。

CoreFoundation API通常返回您需要传递给其他函数的“ baton”指针。您在哪里看到该结构定义?


0
投票

您可以在Xamarin中使用Objective-C方法获取MAC地址,因为C#提供了不同的MAC地址:

[DllImport("/System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration")]
public static extern IntPtr SCNetworkInterfaceCopyAll();

[DllImport("/System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration")]
public static extern IntPtr SCNetworkInterfaceGetHardwareAddressString(IntPtr scNetworkInterfaceRef);

private string MacAddress()
{
        string address = string.Empty;

        using (var interfaces = Runtime.GetNSObject<NSArray>(SCNetworkInterfaceCopyAll()))
        {
            for (nuint i = 0; i < interfaces.Count; i++)
            {
                IntPtr nic = interfaces.ValueAt(i);
                var addressPtr = SCNetworkInterfaceGetHardwareAddressString(nic);

                address = Runtime.GetNSObject<NSString>(addressPtr);

                if (address != null) break;
            }
        }
        return address;
}
© www.soinside.com 2019 - 2024. All rights reserved.