在DLL(C++)中有一个函数原形为
VSCLIB_LoginServer  (OUT int *plHandle,IN ServerAccessInfo *pServerInfo,  IN int Timeout =5000); 
ServerAccessInfo 是一个结构体,原形为
ServerAccessInfo 
{  int m_serverType;      //服务器类型0: 4-channel-server, 1: 1-channel server
    char m_ServerName[32]; //服务器名
    char m_UserName[32];   //用户名 
    char m_Password[32];   //用户密码     
    char m_Url[32];        //IP地址    
    DWORD m_Port;          //端口号
    int m_LinkType;        //连接类型,TCP为1,UDP为2
} 现在我需要在C#中使用这个函数,但老出错.
我的代码如下:
建立ServerAccessInfo :
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
        public struct ServerAccessInfo
        {
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
            public int m_serverType;        //0: 4-channel-server  1: 1-channel server 
            public string m_ServerName;
            public string m_UserName;
            public string m_Password;
            public string m_Url;
            public uint m_Port;              //default port is 3000
            public int m_LinkType;
        }
导入DLL:
[DllImport("VSClientSdk.dll")]       
public static extern int VSCLIB_LoginServer(ref int plHandle, ref IntPtr pServerInfo, int Timeout);   在程序中调用:
            ServerAccessInfo m_ServerAccessInfo = new ServerAccessInfo();
            m_ServerAccessInfo.m_serverType = 1;
            m_ServerAccessInfo.m_Port = 3000;
            m_ServerAccessInfo.m_LinkType = 1;
            m_ServerAccessInfo.m_UserName = "1";
            m_ServerAccessInfo.m_Password = "1";
            m_ServerAccessInfo.m_Url = ip.Text;
            m_ServerAccessInfo.m_ServerName = "dev1";
...........
IntPtr ptr;
int vs_Handle =0;
VSCLIB_LoginServer(ref vs_Handle,ref ptr, 5000);
Marshal.PtrToStructure(ptr,ServerAccessInfo );
程序运行结果出错.
想问问如果DLL中的参数需要从程序中带入一个Struct类型的参数在C#中如何实现.

解决方案 »

  1.   

    unsafe struct ServerAccessInfo
    {
      int   m_serverType;
      fixed byte m_ServerName[32];
      fixed byte m_UserName[32];
      fixed byte m_Password[32];
      fixed byte m_Url[32];
      ushort     m_Port;
      int        m_LinkType;
    }用这个定义看看
      

  2.   

    public static extern int VSCLIB_LoginServer(out int plHandle, ref pServerInfo,int Timeout);