我需要C#字符串的數組傳遞到C代碼元帥使用對一個字符串數組從C#爲C代碼/調用
例C代碼
void print_string_array(const char** str_array, int length){
for (int i = 0; i < length; ++i) {
printf("Sting[%l] = %s\n", i, str_array[i]);
}
}
,我曾嘗試
C#(這沒有工作)
string foo[] = {"testing", "one", "two", "three"};
print_string_array(foo, foo.Length);
[DllImport(my_C_dll, CharSet = CharSet.Ansi)]
private static extern void print_string_array([In][MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPStr)] string[] sa, int length);
與System.AccessViolationException System.AccessViolationException失敗:試圖讀取或寫入保護內存。這通常表明其他內存已損壞。
我也曾嘗試(這還沒有工作)
string[] foo = {"testing", "one", "two", "three"};
IntPtr[] s_array = new IntPtr[foo.Length];
for(int i = 0; i < foo.Length; ++i)
{
s_array[i] = Marshal.StringToCoTaskMemAnsi(foo[i])
}
print_string_array(s_array, s_array.Length);
[DllImport(my_C_dll, CharSet = CharSet.Ansi)]
private static extern void print_string_array(IntPtr[] sa, int length);
這也失敗,出現System.AccessViolationException System.AccessViolationException:嘗試讀取或寫入受保護的內存。這通常表明其他內存已損壞。
任何人都知道如何將字符串數組從C#傳遞給C?
編輯: 添加了來自David Heffernam的每條建議的錯誤消息。 在C代碼中將size_t更改爲int,因爲它不影響我正在嘗試執行的操作。 仍然收到相同的錯誤。
我的原始代碼仍然失敗;然而,我開始了一個乾淨的測試項目,代碼首次嘗試使用這種方法。謝謝。 – gnash117