日期:2014-05-18  浏览次数:21037 次

C#调用C++ dll时,结构体参数类型的转换
C++ 接口如下:
int _stdcall TA_HazyInqAcc(AccountMsg *pAccMsg, int *RecNum , char *FileName,short TimeOut = 10);
结构体如下:
typedef struct
{
  char Name[21]; /*姓名*/
  char SexNo[2]; /*性别*/
  char DeptCode[19]; /*部门代码*/
  unsigned int CardNo; /*卡号*/
  unsigned int AccountNo; /*帐号*/
  char StudentCode[21]; /*学号*/
  char IDCard[21]; /*身份证号*/
  char PID[3]; /*身份代码*/
  char IDNo[13]; /*身份序号*/
  int Balance; /*现余额*/
  char Password[7]; /*消费密码*/
  char ExpireDate[7]; /*账户截止日期*/
  unsigned short SubSeq; /*补助戳*/
  char IsOpenInSys; /*是否在本系统内开通*/
  short TerminalNo; /*终端号码,提取补助时需要填写*/
  short RetCode; /*后台处理返回值*/
  char Flag[16]; /*状态(2004-08-26增加)*/
  char CardType[4]; /*卡类型*/
  char AccType[4];  
  unsigned short UsedCardNum; /*卡片上的用卡次数*/
  long AccAmt;  
  char Pad[70]; /*预留字段*/
} AccountMsg;

我现在这样调用的
[DllImport("AIO_API.dll")]
public static extern int TA_HazyInqAcc(ref read AccMsg, ref int RecNum, byte[] FileName, short TimeOut = 10);

C#定义的结构体
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)]
  public struct AccountMsg 
  {
  [MarshalAs(UnmanagedType.AnsiBStr, SizeConst = 21)]
  public string Name;
  [MarshalAs(UnmanagedType.AnsiBStr, SizeConst = 2)]
  public string SexNo;
  [MarshalAs(UnmanagedType.AnsiBStr, SizeConst = 19)]
  public string DeptCode;
  public UInt32 CardNo;
  public UInt32 AccountNo;
  [MarshalAs(UnmanagedType.AnsiBStr, SizeConst = 21)]
  public string StudentCode;
  [MarshalAs(UnmanagedType.AnsiBStr, SizeConst = 21)]
  public string IDCard;
  [MarshalAs(UnmanagedType.AnsiBStr, SizeConst = 3)]
  public string PID;
  [MarshalAs(UnmanagedType.AnsiBStr, SizeConst = 13)]
  public string IDNo;
  public int Balance;
  [MarshalAs(UnmanagedType.AnsiBStr, SizeConst = 7)]
  public string Password;
  [MarshalAs(UnmanagedType.AnsiBStr, SizeConst = 7)]
  public string ExpireDate;
  public UInt16 SubSeq;
  [MarshalAs(UnmanagedType.AnsiBStr, SizeConst = 1)]
  public char IsOpenInSys;
  public short TerminalNo;
  public short RetCode;
  [MarshalAs(UnmanagedType.AnsiBStr, SizeConst