Na wat onderzoek naar c# i.c.m. pointers, puur uit interesse, kwam ik op een voorbeeld uit. ik heb dit voorbeeld gebruikt in een programma voor mezelf, maar ik weet eigenlijk niet wat nu sneller / efficienter is. De MSDN beschrijft dat het gebruik van unsafe code in c# sneller is dan het gebruik van normale code. Het onderstaande was origineel, en werkte:
C#:
1
2
| [DllImport("iphlpapi.dll", ExactSpelling = true)]
private static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen); |
C#:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| public static bool CheckAddressAvailability(IPAddress addr)
{
byte[] macAddr = new byte[6];
uint macAddrLen = (uint)macAddr.Length;
int res = SendARP(BitConverter.ToInt32(addr.GetAddressBytes(), 0), 0, macAddr, ref macAddrLen);
if ((res == 0 || res == 31))
{
if (macAddr[0] != 0 || macAddr[1] != 0 || macAddr[2] != 0 || macAddr[3] != 0
|| macAddr[4] != 0 || macAddr[5] != 0)
{
return false;
}
}
return true;
} |
Het bovenstaande werkt zoals ik het wil. Nu heb ik het onderstaande gemaakt, wat ook werkt zoals ik het wil
C#:
1
2
| [DllImport("iphlpapi.dll", ExactSpelling = true)]
private static unsafe extern int SendARP(int DestIP, int SrcIP, void* pMacAddr, ref uint PhyAddrLen); |
C#:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| public static unsafe bool CheckAddressAvailability(IPAddress addr)
{
byte[] macAddr = new byte[6];
uint macAddrLen = (uint)macAddr.Length;
fixed (byte* ptr = macAddr)
{
int res = SendARP(BitConverter.ToInt32(addr.GetAddressBytes(), 0), 0, ptr, ref macAddrLen);
if ((res == 0 || res == 31))
{
if (macAddr[0] != 0 || macAddr[1] != 0 || macAddr[2] != 0 || macAddr[3] != 0
|| macAddr[4] != 0 || macAddr[5] != 0)
{
return false;
}
}
}
return true;
} |
De vraag die mij nu berust: Wat is sneller?