[英]byte[] to byte* in C#
我創建了2個程序 - 在C#和C ++中,都從C dll調用本機方法。 C ++工作正常,因為有相同的數據類型,C#不起作用。
而native函數參數是unsigned char*
。 我在C#中嘗試了byte[]
,它沒有用,然后我嘗試了:
fixed(byte* ptr = byte_array) {
native_function(ptr, (uint)byte_array.Length);
}
它也行不通。 以這種方式將字節數組轉換為byte*
是否正確? 它是正確的在C#中使用字節作為unsigned char
用C?
編輯:這東西返回錯誤的結果:
byte[] byte_array = Encoding.UTF8.GetBytes(source_string);
nativeMethod(byte_array, (uint)byte_array.Length);
這個東西也會返回錯誤的結果:
byte* ptr;
ptr = (byte*)Marshal.AllocHGlobal((int)byte_array.Length);
Marshal.Copy(byte_array, 0, (IntPtr)ptr, byte_array.Length);
unsafe class Test
{
public byte* PointerData(byte* data, int length)
{
byte[] safe = new byte[length];
for (int i = 0; i < length; i++)
safe[i] = data[i];
fixed (byte* converted = safe)
{
// This will update the safe and converted arrays.
for (int i = 0; i < length; i++)
converted[i]++;
return converted;
}
}
}
您還需要在構建屬性中設置“使用不安全代碼”復選框。
你必須編組byte[]
:
[DllImport("YourNativeDLL.dll")]
public static extern void native_function
(
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]
byte[] data,
int count // Recommended
);
您可以分配一個非托管數組並使用Marshal.Copy
將托管byte[]
數組的內容復制到一個非托管的unsigned char*
數組。 請注意,必須手動清除非托管資源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.