C# - 为什么我需要初始化一个 [Out] 参数

标签 c# pinvoke marshalling out

我有几个从 native .dll 导入的方法,使用以下语法:

internal static class DllClass {
    [DllImport("Example.dll", EntryPoint = "ExampleFunction")]
    public static extern int ExampleFunction([Out] ExampleStruct param);
}

现在,因为我将 param 指定为 [Out],所以我希望至少以下片段之一是有效的:

ExampleStruct s;
DllCass.ExampleFunction(s);

ExampleStruct s;
DllCass.ExampleFunction([Out] s);

ExampleStruct s;
DllCass.ExampleFunction(out s);

然而,它们都不起作用。我发现让它工作的唯一方法是初始化 s。

ExampleStruct s = new ExampleStruct();
DllCass.ExampleFunction(s);

我已通过将第一个代码段重写为以下代码来设法解决此问题,但这感觉有点多余。

internal static class DllClass {
    [DllImport("Example.dll", EntryPoint = "ExampleFunction")]
    public static extern int ExampleFunction([Out] out ExampleClass param);
}

我读过 What's the difference between [Out] and out in C#?并且因为接受的答案指出 [Out]out 在上下文中是等效的,这让我想知道为什么它对我不起作用以及我的“解决方案”是合适的。

我应该同时使用两者吗?我应该只使用 out 吗?我应该只使用 [Out] 吗?

最佳答案

OutAttribute 确定参数的运行时 行为,但它对编译时 没有影响。如果要使用编译时语义,则需要 out 关键字。

仅使用 out 关键字将更改运行时编码(marshal)处理,因此 OutAttribute 是可选的。参见 this answer了解更多信息。

关于C# - 为什么我需要初始化一个 [Out] 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26653250/

相关文章:

c# - 如何让这个 LINQ to XML 查询更加优雅?

c# - Newtonsoft.Json 解析不正确的json

c# - 通过 UDP 连接在 C# 中读取此 C++ 编码数据

c# - 使用 Portable.Licensing 如何验证属性硬件 Id

c# - 无法使用 margin "Thickness"值

c++ - 是否可以在没有 for 循环的情况下将 native 结构数组编码为托管数组

c# - 如何用TWAIN获取扫描仪的序列号?

c# - 当您从 C# 进行 P/调用时,异步过程调用如何处理编码(marshal)的委托(delegate)?

java - JAXB 静态编码与 JAXBContext createMarshaller()

c# - 为什么 Marshal.WriteInt64 方法的代码如此复杂?