TechnikEmpire / DivertPInvoke

PInvoke wrapper for WinDivert
GNU Lesser General Public License v3.0
24 stars 12 forks source link

[Question] Unsafe WinDivertHelperParsePacket #9

Closed wreighsantos closed 6 years ago

wreighsantos commented 6 years ago

Hi, since you've pointed me to this, may I ask a question?

I'm trying to use your PInvoke but I'm having trouble using its WinDivertHelperParsePacket.

Right now I'm using it like this:

WINDIVERT_IPHDR iphdr = new WINDIVERT_IPHDR();
WINDIVERT_IPV6HDR ipv6hdr = new WINDIVERT_IPV6HDR();
WINDIVERT_ICMPHDR icmphdr = new WINDIVERT_ICMPHDR();
WINDIVERT_ICMPV6HDR icmpv6hdr = new WINDIVERT_ICMPV6HDR();
WINDIVERT_TCPHDR tcphdr = new WINDIVERT_TCPHDR();
WINDIVERT_UDPHDR udphdr = new WINDIVERT_UDPHDR();
byte[] data = new byte[DEFAULT_BUFFER_SIZE];
uint dataLen = 0;

WinDivertMethods.WinDivertHelperParsePacket(packet, readLen, &iphdr, &ipv6hdr, &icmphdr, &icmpv6hdr, &tcphdr, &udphdr, data, &dataLen);

Where packet is the byte array from WinDivertRecv. Obviously this won't work because there is a parameter mismatch, can you point out to me where I went wrong?

Also, is there a way to make it safe? Like, changing from * to ref, In or Out? I'm really sorry for my ignorance, I'm new to this and currently I'm just investigating. I would be happy to do it by myself.

Thank you very much!

wreighsantos commented 6 years ago

I've tried changing the function signature to:

public static unsafe extern bool WinDivertHelperParsePacket(byte[] pPacket, uint packetLen,
    ref WINDIVERT_IPHDR ppIpHdr, ref WINDIVERT_IPV6HDR ppIpv6Hdr,
    ref WINDIVERT_ICMPHDR ppIcmpHdr, ref WINDIVERT_ICMPV6HDR ppIcmpv6Hdr,
    ref WINDIVERT_TCPHDR ppTcpHdr, ref WINDIVERT_UDPHDR ppUdpHdr, byte[] ppData,
    ref uint pDataLen);

I've ran my sample code and it ran well. Now I can remove the unsafe I suppose.

Is this safe? Or are there any reasons why it was left like that?

[UPDATE]

I was wrong, I removed the double pointers in the function signature, I thought those were wrong. Ended up they were correct. Sorry for the inconvenience!

TechnikEmpire commented 6 years ago

No problem. Yeah unfortunately we need to use unsafe because the API uses pointers to pointers so it's not as simple as just using an array of bytes.

Remember though that "unsafe" isn't unsafe by nature. It's a poor choice of words. Every last piece of software on your computer, including .net is using pointers. Just stuff your unsafe code into a library and then reference the library and you won't need to make to enable unsafe on the application referencing the "unsafe" library if need be. :)