I've been spending the past week working on Mac which is very close to FreeBSD, and I have been working on the simple goal of getting a MAC address for a network interface. I was able to find plenty of sample code on the net on how to do it, but they were all written in C. My gaol then became to do the same thing in C# using P/Invoke and Marshalling. I've been working on this for three days and I have learned two things. One, P/Invoke and Marshalling is extremely hard and confusing because you lose code reuse, meaning that every structure has to be redefined, along with macros and function signatures. System level code uses tons of nested structures, and defined variables and so on. So implementating just one P/Invoke function which takes a structure can get messy really quickly. I guess back then developers assumed everyone would be using header files which would automatically resolve all of these special structures macros and so on.
The second thing that I learned is that trying to work with pointers in C# is (dangerous) and extremely annoying. C allows developers to do many hackish things with pointers in order to cast, or just to different places in memory and so on. C# has various limitations on how to use pointers; so there is no direct mapping from C pointer handling to C# pointer handling. With that said, once again, converting system level C code to C# requires good understanding and experience with C pointers, and C# marshalling in order to get things done. Overall, I'm learning a lot, and spending a lot of time learning about different marshalling options but I did not expect it to be this hard. Also, marshalling tends to get confusing because they are so many different ways to represent data, you have IntPtr, char arrays, byte arrays, keywords such as in, out, ref, and functions such as Marshal.PtrToStructure, Marshal.Copy, Marshal.ReadByte, and so much stuff.
In the end, my advice is, do not underestimate marshalling (or anything else in programming), and pointers are extremely annoying to deal with. So try to avoid marshalling and pointers as much as possible
No comments:
Post a Comment