4 ms·
P/Invoke is not that bad - you basically just copy the c header declaration and adjust a bit. It starts to be interesting strings or large memory where you want
by yread 6y ago
P/Invoke is not that bad - you basically just copy the c header declaration and adjust a bit. It starts to be interesting strings or large memory where you want to avoid copying it too much. Doing it cross-platform is a bit of pain (basically copy everything and point it to different library - .dll vs .so) it would be nice if there was a better way. I still haven't figured out how to get unicode strings to work cross platform though.
- int_19h 6y agoOne trick is to avoid smart marshaling (for C# strings, arrays etc), and use "unsafe" and raw pointers. This way, all your types are what CLR calls blittable - i.e. their representation is the same in native and managed - and the behavior is straightforward and predictable, as no copying or implicit conversions occur. This is particularly useful for cases when you have something like a struct containing a pointer to a struct containing a string, and when ownership of memory is unclear. Of course, the downside is that you have to do all the marshaling yourself then. E.g. for strings, you use the appropriate System.String constructor to create one from a raw pointer - it has overloads for null-terminated string pointers as well as pointer + length, and you can specify encoding too. Or, to pass the string to native, you pin it using "fixed" to obtain a pointer.
- skeletonjelly 6y agoVery interesting! Do you have a link or quick example you could please share?
- int_19h 6y agoIf you have any specific Win32 API in mind, I could write up a snippet to invoke it in this manner.