I have an external library that takes an IntPtr. Is there any safe way to do this…
int BytesWritten = 0;
Output.WriteBytes(buffer, new IntPtr(&BytesWritten));
…without having to use ‘unsafe’ code? I’m not that familiar with IntPtrs, but I’d like to do something like this:
fixed int BytesWritten = 0;
Output.WriteBytes(buffer, IntPtr.GetSafeIntPtr(ref BytesWritten));
…in such a way that I don’t need to compile with /unsafe.
I can’t change the WriteBytes function, it’s an external function.
It seems like there should be some sort of cast between ‘ref int’ and IntPtr, but I have not had luck finding it.
Yes, there is. You can use P/Invoke for your code. It will create the pointer for you automagically. Something like this:
(I added the array as a bonus). More info on P/Invoke can be found, with gazillion examples, at pinvoke.net.
Each parameter above can take
out,inandref. Out and ref parameters are translated as pointers, where an ref-parameter is two-way.