如何:指定 out 参数

此示例说明如何将函数参数指定为 out 参数,以及如何从 C# 程序调用该函数。

在 C++ 中使用 OutAttribute 指定 out 参数。

示例

此示例的第一部分创建了一个 C++ DLL。 它定义了一个包含带 out 参数的函数的类型。

// cpp_out_param.cpp
// compile with: /LD /clr
using namespace System;
public value struct TestStruct {
   static void Test([Runtime::InteropServices::Out] String^ %s) {
      s = "a string";
   }
};

此源文件是一个 C# 客户端,它使用在上一个示例中创建的 C++ 组件。

// cpp_out_param_2.cs
// compile with: /reference:cpp_out_param.dll
using System;
class TestClass {
   public static void Main() {
      String t;
      TestStruct.Test(out t);
      System.Console.WriteLine(t);
   }
}
a string

另请参阅

使用 C++ 互操作(隐式 PInvoke)