如何在 C CLI 中从数组<无符号短>复制到无符号短 []?
How do I copy from an array<unsigned short> to an unsigned short[] in C CLI?
我正在为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];
这仅影响属性 - 在为调用编制索引时,返回托管数组的函数似乎按预期工作。
相关文章:
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 将无符号char*转换为std::istream*C++
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- C++中无符号字符溢出
- 使用无符号字符数组有效存储内存
- 如何打印boost多精度128位无符号整数
- C++模板函数,用于比较任何无符号整数和有符号整数
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 获取隐式转换溢出从无符号到已签名的警告
- 如何在保持其值的同时将 c++ 无符号字符变量转换为 char 变量
- 从 std::vector<无符号字符>切片中提取 int?
- 是什么导致了这种使用三进制而不是短整型的有符号int到无符号int转换
- 无法在 Arduino 中uint8_t数组转换为无符号长整型数组
- 将无符号字符的向量存储在数组中会给我 std::bad_alloc
- 使用 fopen 打开 .pak 文件并使该文件应用于 const 无符号字符* (C++)
- C4018:类内有符号、无符号不匹配
- C++无符号短裤的划分导致 int
- 库特无符号字符