c++中的代码:结构体:
typedef struct
{
   unsigned char strChkFlg;             /* 验证类型 3-TAC校验 4-TAC生成 等*/
   unsigned char strTac[14];            /* 验证码 */
} enc_def;函数:
int SoftGenTac(enc_def  *pstrInMsg)
{
~~~~~~~~~~~
}
----------------------------------------------
c#对应的
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
        public struct enc_def
        {
            public byte strChkFlg;   /* 验证类型 3-TAC校验 4-TAC生成 等*/            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 14)]
            public Byte[] strTac;    /* 验证码 */
        }        [DllImport("fepEnc.dll", EntryPoint = "?SoftGenTac@@YAHPAUkey_info_def@@PAUenc_ipc_def@@@Z", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        public static extern int SoftGenTac(ref enc_def  pstrInMsg);调用方法里赋值
        enc_def encIpc = new enc_def();
        encIpc.strChkFlg = Convert.ToByte("4", 16);         encIpc.strTac = Encoding.Default.GetBytes("12312313212325");//加了这句,下面调用时候就报"未能封送类型,因为嵌入数组实例的长度与布局中声明的长度不匹配"
        int result = SoftGenTac(ref encIpc);请哪位达人,遇到并处理同样问题的?

解决方案 »

  1.   

    你的结构体有问题,应该这样申明:    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
        public struct enc_def
        {
            public char strChkFlg;  /* 验证类型 3-TAC校验 4-TAC生成 等*/        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
            public string strTac;    /* 验证码 */
        } 接下来的赋值操作我想应该没有问题了吧。
      

  2.   

    同LS..
    另外从你导入的函数名来看...
    用StdCall没问题吗?
      

  3.   

    CharSet定义在结构中的字符串成员在结构被传给DLL时的排列方式。可以是Unicode、Ansi或Auto。     
      默认为Auto,在WIN   NT/2000/XP中表示字符串按照Unicode字符串进行排列,在WIN   95/98/Me中则表示按照ANSI字符串进行排列。