首页 > 解决方案 > C++/WinRT 数据不正确的数据编组

问题描述

C++/WinRT 新手,在尝试使用 C++/WinRT 导出单个 C++ 类以在 .Net 应用程序中使用时遇到一些问题。

我在 Visual Studio 2017 v15.7.4 中创建了一个 C++ Windows 运行时组件(Windows 通用)。

这是我尝试使用的 C++ 函数的签名,因为它存在于我复制到 C++/WinRT 项目中的头文件中

public:
short Carryout(unsigned char* p, unsigned short* pCh1, unsigned short* pCh2, unsigned short* pCh3, unsigned char* pCePa, unsigned short* pTAc);

如果它的重要上下文,该函数将字节数组 p 作为输入,并输出从它派生的 5 个数组:pCh1、pCh2、pCh3、pCePa、pTAc。

现在在 .Net 应用程序中,我从 WinRT 声明了该类的新实例并设置了所有缓冲区,仅作为示例:

byte[] dataBlock = GetDataBlock();
ushort[] ch1s = new ushort[4096];
ushort[] ch2s = new ushort[4096];
ushort[] ch3s = new ushort[4096];
byte[] cepa = new byte[4096];
ushort[] tac = new ushort[1024];

WinRTClass wrtClass = new WinRTClass();
short x = wrtClass.Carryout(dataBlock, out ch1s, out ch2s, out ch3s, out cepa, out tac);

VS 告诉我这是不正确的,因为签名不匹配。检查 Carryout 函数的定义会显示(我假设是)一个自动生成的头文件(在其描述中有“来自元数据”)并且其中的 Carryout 函数的签名完全不同:

public short Carryout(out byte p, out ushort pCh1, out ushort pCh2, out ushort pCh3, out byte pCePa, out ushort pTAc);

请注意,函数参数不是数组,而是 byte/ushort 类型。此外,第一个参数不应该是out类型。解决此自动生成的标头的这种差异的正确方法是什么?

我宁愿不对 C++ 代码进行任何更改:它内部具有相当复杂的数据操作,并且很容易数十年的运行时间确保它一切正常。

先感谢您!

标签: c++windows-runtimemarshallingwinrt-componentc++-winrt

解决方案


C/C++ 中的指针类似于 C# 中的引用(允许修改的单词“out”)。将它与数组结合起来,它会为您提供:

public short Carryout(out byte[] dataBlock, out ushort[] ch1s, out ushort[] ch2s, out ushort[] ch3s, out byte[] cepa, out ushort[] tac);

推荐阅读