array<Byte>^ TO unsigned char* :: Marshall class - Interop Issue

这一生的挚爱 提交于 2020-01-03 03:37:17

问题


I wanted to convert array< Byte>^ to unsigned char*. I have tried to explain what i have done. I donot know how to proceed further. Please show me the right approach. I am using MS VC 2005.

//Managed array  
array<Byte>^ vPublicKey = vX509->GetPublicKey();

//Unmanaged array
unsigned char        vUnmanagedPublicKey[MAX_PUBLIC_KEY_SIZE]; 
ZeroMemory(vUnmanagedPublicKey,MAX_PUBLIC_KEY_SIZE);

//MANAGED ARRAY to UNMANAGED ARRAY  

// Initialize unmanged memory to hold the array.  
vPublicKeySize = Marshal::SizeOf(vPublicKey[0]) * vPublicKey->Length;  
IntPtr vPnt = Marshal::AllocHGlobal(vPublicKeySize);

// Copy the Managed array to unmanaged memory.  
Marshal::Copy(vPublicKey,0,vPnt,vPublicKeySize);

Here vPnt is a number. But how can copy the data from vPublicKey in to vUnmanagedPublicKey.

Thank you
Raj


回答1:


Try replacing your last two lines with this:

Marshal::Copy(vPublicKey, 0, IntPtr(vUnmanagedPublicKey), vPublicKeySize);

You have already allocated a buffer in unmanaged memory to copy the key to, so there is no need to allocate unmanaged memory using AllocHGlobal. You just needed to convert your unmanaged pointer (vUnmanagedPublicKey) to a managed pointer (IntPtr) so that Marshal::Copy could use it. IntPtr takes a native pointer as one of the arguments to its constructor to perform that conversion.

So your full code could look something like this:

array<Byte>^ vPublicKey = vX509->GetPublicKey();
unsigned char        vUnmanagedPublicKey[MAX_PUBLIC_KEY_SIZE]; 
ZeroMemory(vUnmanagedPublicKey, MAX_PUBLIC_KEY_SIZE);

Marshal::Copy(vPublicKey, 0, IntPtr(vUnmanagedPublicKey), vPublicKey->Length);



回答2:


Instead of using the marshalling-API it is easier to just pin the managed array:

array<Byte>^ vPublicKey = vX509->GetPublicKey();
cli::pin_ptr<unsigned char> pPublicKey = &vPublicKey[0];

// You can now use pPublicKey directly as a pointer to the data.

// If you really want to move the data to unmanaged memory, you can just memcpy it:
unsigned char * unmanagedPublicKey = new unsigned char[vPublicKey->Length];
memcpy(unmanagedPublicKey, pPublicKey, vPublicKey->Length);
// .. use unmanagedPublicKey
delete[] unmanagedPublicKey;


来源:https://stackoverflow.com/questions/1012396/arraybyte-to-unsigned-char-marshall-class-interop-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!