如何:在 /clr 编译中使用本机类型

可以在 /clr 编译中定义本机类型,并且程序集中对该本机类型的任何使用都有效。 但是,本机类型将不能用于引用的元数据。

每个程序集必须包含要使用的每个本机类型的定义。

有关详细信息,请参阅 /clr(公共语言运行时编译)

示例

此示例创建一个定义和使用本机类型的组件。

// use_native_type_in_clr.cpp
// compile with: /clr /LD
public struct NativeClass {
   static int Test() { return 98; }
};

public ref struct ManagedClass {
   static int i = NativeClass::Test();
   void Test() {
      System::Console::WriteLine(i);
   }
};

此示例定义一个使用该组件的客户端。 请注意,除非在编译单位中定义本机类型,否则访问本机类型是错误的。

// use_native_type_in_clr_2.cpp
// compile with: /clr
#using "use_native_type_in_clr.dll"
// Uncomment the following 3 lines to resolve.
// public struct NativeClass {
//    static int Test() { return 98; }
// };

int main() {
   ManagedClass x;
   x.Test();

   System::Console::WriteLine(NativeClass::Test());   // C2653
}

另请参阅

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