[英]Marshal a C char[][] array to C#
我看了看,嘗試了一切我能想到或已經找到的建議。 我仍然沒有運氣獲得我需要的數據。
我正在使用第三方DLL,我認為它是用C語言編寫的。我需要在C#中訪問此DLL中的函數。 在大多數情況下,我有這個工作,除了一個功能。 我遇到問題的函數有以下標題:
uint queryNumOfServers(USHORT *NumOfServers, char ServerNames[8][16]);
我在C#應用程序中聲明了以下內容
[DllImport("client.dll", CharSet=CharSet.Ansi]
public static extern uint queryNumOfServers(ref short numberofServer, StringBuilder serverNames);
我這稱之為:
StringBuilder serverNames = new StringBuilder(128);
short numServers = -1;
queryNumberOfServers(ref numServers, serverNames);
問題是,雖然numberOfServers返回等於4,但我只在serverNames中獲得一個名稱。 我在一個小C程序中測試了上面的C函數。 我得到了numberOfServer = 4,但我還得到了4個名字。
我試過以下但沒有成功:
[DllImport("client.dll", CharSet=charSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern uint queryNumOfServers(ref short numberOfServer,[MarshalAs(UnmanagedType.LPStr)] string serverNames);
稱之為
string serverNames = new string('\0', 128);
queryNumOfServers(ref numServers, serverNames);
使用此選項對serverNames沒有任何更改。
開發環境是Visual Studio 2008。
經過多次搜索和拔毛,這是對我有用的解決方案。
在我的C#應用程序中聲明了函數頭:
[DllImport("client.dll", CharSet = CharSet.Ansi)]
public static extern uint queryNumOfServers(ref short numberOfServers, [MarshalAs(UnmanagedType.LPArray)] byte[,] serverNames);
然后調用如下:
byte[,] serverNames = new byte[8,16];
short numServers = -1;
queryNumberOfServers(ref numServers, serverNames);
這將返回一個雙索引字節數組。 從這里我使用Buffer.BlockCopy()和Encoding.UTF8.GetString()將我的字節數組轉換為字符串數組。
我會使用[StructLayout(LayoutKind.Sequential...]
和[MarshalAs(UnmanagedType.ByValTStr...]
。
這是兩個很好的例子:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.