C#Interop:out params也可以为null

unk*_*ser 1 c# interop

考虑以下DllImport:

[DllImport("lulz.so")]
public static extern int DoSomething(IntPtr SomeParam);
Run Code Online (Sandbox Code Playgroud)

这实际上引用了这样的C风格函数:

int DoSomething(void* SomeParam); 
Run Code Online (Sandbox Code Playgroud)

考虑SomeParam是一个"out"参数,但也可以是NULL.如果param为NULL,则C函数的行为会有所不同.所以我可能想要:

[DllImport("lulz.so")]
public static extern int DoSomething(out IntPtr SomeParam);
Run Code Online (Sandbox Code Playgroud)

但是,如果我在导入中将它设为out参数,我就无法将其传递为NULL,即我不能这样做:

int retVal = DoSomething(IntPtr.Zero)
Run Code Online (Sandbox Code Playgroud)

我有什么选择?

Ada*_*son 8

如果您尝试传递值,则out不是正确的关键字; 改为ref.您仍然需要显式传递变量,但它可以作为null参考.

例如...

[DllImport("lulz.so")]
public static extern int DoSomething(ref IntPtr SomeParam);
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样调用它:

IntPtr retVal = IntPtr.Zero;

DoSomething(ref retVal);
Run Code Online (Sandbox Code Playgroud)

然而

什么告诉你它需要是outref?传递IntPtras out或者ref实际上类似于传递双指针.将参数作为一个传递实际上似乎更合适IntPtr.

典型的过程是在托管代码中分配必要的内存并传递IntPtr表示已分配的内存,或者IntPtr.Zero表示空指针.您不需要传递IntPtras outref以便将数据发送回.NET; 如果你正在调用的函数实际上会改变指针的地址,你只需要这样做.