How can I pass a pointer to an array using p/invoke in C#?

后端 未结 3 747
轻奢々
轻奢々 2020-11-30 06:32

Example C API signature:

void Func(unsigned char* bytes);

In C, when I want to pass a pointer to an array, I can do:

unsigned ch         


        
3条回答
  •  悲哀的现实
    2020-11-30 07:13

    You can use unsafe code:

    unsafe 
    {
         fixed(byte* pByte = byteArray)
         IntPtr intPtr = new IntPtr((void *) pByte);
         Func(intPtr);
    }
    

    If you need to use safe code, you can use a few tricks:

    IntPtr intPtr = Marshal.AllocHGlobal(Marshal.SizeOf(byteArray));
    Marshal.Copy(byteArray, 0, intPtr, Marshal.SizeOf(byteArray));
    
    Func(intPtr);
    
    Marshal.FreeHGlobal(intPtr);
    

    However, the safe code is going to be slow IMHO.

提交回复
热议问题