如何:指定 out 參數

此範例示範如何指定函式參數是 out 參數,以及如何從 C# 程式呼叫該函式。

out使用 OutAttribute 在 C++ 中指定參數。

範例

此範例的第一個部分會建立 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++ Interop (隱含 PInvoke)