Memcpy of native array to managed array in C++ CLI

前端 未结 2 1742
忘了有多久
忘了有多久 2021-01-12 03:32

Am I doing this right?

I get a pointer to a native array and need to copy to a managed array. Use memcpy() with a pin_ptr.

unsigned char* pArray;
uns         


        
相关标签:
2条回答
  • 2021-01-12 03:56

    You are doing it almost right:

    pin_ptr<Byte> pinPtrArray = &ManagedClass.ByteArray[ManagedClass.ByeArray->GetLowerBound(0)];
    

    Marshal::Copy is not safe and not as fast. Always use pinned pointers in managed C++.

    Edit: If you want to, you can check the length to make sure the memcpy won't exceed the bounds first, e.g.:

    if (arrayCount > ManagedClass.ByteArray.Length)
        (throw Out of bounds copy exception)
    
    0 讨论(0)
  • 2021-01-12 03:58

    That works, but isn't safe. You'll blow the garbage collected heap to smithereens when you get arrayCount wrong. Very hard to diagnose.

    Marshal::Copy() is safe and just as fast.

    0 讨论(0)
提交回复
热议问题