如何在 C CLI 中从数组<无符号短>复制到无符号短 []?

How do I copy from an array<unsigned short> to an unsigned short[] in C CLI?

本文关键字:无符号 gt 复制 lt CLI 数组      更新时间:2023-10-16

我正在为C API开发C++ CLI包装器。 C API 有一个结构,其中包含一个由四个无符号短裤和一个由四个整数组成的数组。 因此,我为 C# 代码创建了一个类似的类,以便在调用包装器函数时使用。

// C Structure
typedef struct c_Struct_
{
  unsigned short   uShorts[4];
  int     ints[4];
} c_Struct;

// C++ CLI Class
public ref class CliClass
{
public:
  property array<unsigned short>^ UnsignedShorts
  {
    array<unsigned short>^ get()
    {
      return _unsignedShorts;
    }
  }
  property array<int>^ Ints
  {
    array<int>^ get()
    {
      return _ints;
    }
  }
  CliClass(array<unsigned short>^ us, array<int> i)
  {
    _unsignedShorts = us;
    _ints = i;
  }
private:
  array<unsigned short>^ _unsignedShorts;
  array<int>^ _ints;
}

现在我们来回答我的问题。 我在 CLI 类中添加了一个内部方法来创建一个结构:

internal:
  c_Struct ToStruct()
  {
    c_Struct results;
    results.uShorts[0] = UnsignedShorts[0];
    results.uShorts[1] = UnsignedShorts[1];
    results.uShorts[2] = UnsignedShorts[2];
    results.uShorts[3] = UnsignedShorts[3];
    results.ints[0] = Ints[0];
    results.ints[1] = Ints[1];
    results.ints[2] = Ints[2];
    results.ints[3] = Ints[3];
    return results;
  }

但我收到错误:智能感知:对于每个分配,无法将"系统::对象^"类型的值分配给类型为"无符号短"的实体。 正确的语法是什么?

首先取消引用类型的装箱,请尝试以下操作:

results.uShorts[0] = (unsigned short)UnsignedShorts[0];

代码是正确的,你会看到你的程序编译得很好。 没有任何东西被装箱。 这是智能感知解析器中的一个错误。 一个相当奇怪的,很难想象它是如何摸索的。 并非完全罕见,解析器是由另一家公司制造的。 爱迪生设计小组,以编写唯一能够正确实现C++03标准的编译器而闻名。 不过,C++/CLI 会让他们胃灼热。

两种基本的解决方法,您可以使用字段而不是属性:

   c_Struct ToStruct() {
        c_Struct results;
        results.uShorts[0] = _unsignedShorts[0];
        // etc...
   }

但这并不能解决使用该类的代码时遇到的问题。 您可以改为将它们设置为索引属性:

property unsigned short UnsignedShorts[int]
{
    unsigned short get(int index) {
        return _unsignedShorts[index];
    }
}
// Same for the Ints property.

另一种解决方法是先分配给临时局部变量。

array<int> ^temp = ArrayOfIntsProperty;
int j = temp[0];

这仅影响属性 - 在为调用编制索引时,返回托管数组的函数似乎按预期工作。