C ++将包含字符串成员的struct数组返回到c#

时间:2018-04-17 18:11:55

标签: c# c++ dll struct dllimport

我需要在Wince 7中从c ++ DLL返回结构数组到c#。

C ++代码

struct AvailableNetworkList
{
   char strProfileName[7];
   ULONG WLanSignalQuality;
};

BOOL GetAvailableNetworkLists(OUT AvailableNetworkList** data,OUT int *length)
{
      AvailableNetworkList availableNetwork;
      AvailableNetworkList *availableNetworkList = new AvailableNetworkList[pList->dwNumberOfItems];

      for(DWORD i=0;i<pList->dwNumberOfItems;i++)
      {
         availableNetwork.WLanSignalQuality=pList->Network[i].wlanSignalQuality;
         availableNetwork.strProfileName[0] = 'a';
         availableNetwork.strProfileName[1] = 'b';
         availableNetwork.strProfileName[2] = 'c';
         availableNetwork.strProfileName[3] = 'd';
         availableNetwork.strProfileName[4] = 'e';
         availableNetwork.strProfileName[5] = 'f';
         availableNetwork.strProfileName[6] = 'g';
         availableNetworkList[i] = availableNetwork;

      }
      *length=pList->dwNumberOfItems;
      *data = availableNetworkList;
      return true;
};

c#c​​ode

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode), Serializable]
    unsafe struct AvailableNetworkList
    {
        public uint WLanSignalQuality;
        [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 7)]
        public string strProfileName;
    }

    [DllImport("WLANWRAPPER.dll")]
    public static extern bool GetAvailableNetworkLists(out IntPtr arrayPtr, out int size);

使用c#结构调用api和同步数据的代码

            IntPtr resultPtr = IntPtr.Zero;
            int size = 0;
            bool result2 = GetAvailableNetworkLists(out resultPtr, out size);

            var dataEntrySize = Marshal.SizeOf(typeof(AvailableNetworkList));
            var availableNetworkList = new AvailableNetworkList[size];
            for (var i = 0; i < size; i++)
            {
                var cur = (AvailableNetworkList)Marshal.PtrToStructure(resultPtr, typeof(AvailableNetworkList));
                availableNetworkList[i] = cur;
                resultPtr = new IntPtr(resultPtr.ToInt32() + dataEntrySize);
            }

这里一切正常。只有问题是结构中的字符串值(strProfileName)在c ++中设置为“abcdefg”,当涉及到c#时,该值不是可读格式,如下图所示。其他整数值是对的。

enter image description here

任何帮助都将不胜感激。谢谢。

0 个答案:

没有答案