Consider the following DllImport:
[DllImport("lulz.so")]
public static extern int DoSomething(IntPtr SomeParam);
This is actually referencing a C style function like this:
int DoSomething(void* SomeParam);
Consider that SomeParam is an “out” param, but can also be NULL. The C function behaves differently if the param is NULL. So I would probably want:
[DllImport("lulz.so")]
public static extern int DoSomething(out IntPtr SomeParam);
But, if I make it an out param in my import, I cannot pass it NULL, i.e. I can’t do this:
int retVal = DoSomething(IntPtr.Zero)
What are my options here?
If you’re trying to pass a value, then
outis not the right keyword; change it toref. You’ll still need to explicitly pass a variable, but it can be anullreference.For example…
You can then call it like this:
However
What is telling you that it needs to be either
outorref? Passing anIntPtrasoutorrefis really akin to passing a double pointer. It would actually seem more appropriate to pass the parameter as anIntPtr.The typical procedure is either to allocate the necessary memory in managed code and pass an
IntPtrrepresenting that allocated memory, orIntPtr.Zeroto represent a null pointer. You do not need to pass theIntPtrasoutorrefin order to send data back to .NET; you only need to do that if the function you’re calling would actually change the pointer’s address.