如果DLL介面的輸入參數為char**,也就是字元數組的數組(即字串數組),此時在C#聲明中不能直接傳遞string[],傳遞的應該是通過Encoding類對這個string[]進行編碼後得到的一個char[]。
如果DLL介面的輸出參數為char**,也就是字元數組的數組(即字串數組),此時在C#聲明中應該使用byte[]來做參數。然後通過Encoding類對這個byte[]進行解碼,得到字串。如下例所示:
C++ DLL介面:long _stdcall USE_GetAgentGroupInfoEx(/* [in] */ char** AgentID,/* [in] */ long ArraySize,/* [out] */ char** AgentName,/* [out] */ long AgentStatus[],/* [out] */ char** AgentDN,/* [out] */ char** AgentIP);C#中的聲明[DllImport("ProxyClientDll")]public static extern int USE_GetAgentGroupInfoEx(/*[in]*/ char[] allAgentID, /*[in]*/ int agentCount, /*[out]*/ byte[] AgentName,/*[out]*/ int[] AgentStatus,/*[out]*/ byte[] AgentDN,/*[out]*/ byte[] AgentIP);C#中的調用:Encoding encode = Encoding.Default;byte[] tAgentID;byte[] tAgentName;int[] tAgentStatus;byte[] tAgentDN;byte[] tAgentIP;int rslt = -1;int agentCount;//agentID:是個外部定義的string[]類型變數//AgentName:是個外部定義的string[]類型變數//AgtIDLength:是C++ DLL中定義的存放AgtID的char[]的長度//AgtNameLength:是C++ DLL中定義的存放AgtName的char[]的長度//AgtDNLength:是C++ DLL中定義的存放AgtDN的char[]的長度//AgtIPLength:是C++ DLL中定義的存放AgtIP的char[]的長度if (agentID.Length > 0){agentCount = agentID.Length;tAgentID = new byte[AgtIDLength * agentCount];tAgentName = new byte[AgtNameLength * agentCount];tAgentStatus = new int[agentCount];tAgentDN = new byte[AgtDNLength * agentCount];tAgentIP = new byte[AgtIPLength * agentCount];for( int i = 0; i < agentCount; i ++ ){encode.GetBytes(agentID[i]).CopyTo(tAgentID,i*AgtIDLength);}rslt = USE_GetAgentGroupInfoEx(encode.GetChars(tAgentID),agentCount,tAgentName, tAgentStatus, tAgentDN, tAgentIP);if( rslt == 0 ){for( int i = 0; i < agentCount; i ++ ){AgentName[i] = encode.GetString(tAgentName,i*AgtNameLength,AgtNameLength);//……}}}
對於基本的數實值型別的資料,如果是輸入參數,則直接按值傳遞,如果是輸出參數,則需要按引用傳遞(加ref 修飾)。
不論什麼類型的數組,傳遞時實際上都是按引用傳遞,所以不需要再用ref修飾,否則會出錯。對於傳出型參數,在調用前要記得指派足夠的空間。