我想数组转换<字节> ^为unsigned char *。 我试图解释我做了什么。 我知道DONOT如何进一步进行。 请告诉我正确的方法。 我使用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);
这里vPnt是一个数字。 但如何才能在以vUnmanagedPublicKey复制从vPublicKey数据。
谢谢
拉吉
尝试用这种替代你的最后两行:
Marshal::Copy(vPublicKey, 0, IntPtr(vUnmanagedPublicKey), vPublicKeySize);
您已经分配的非托管内存复制的关键缓冲,所以没有必要分配使用AllocHGlobal非托管内存。 你只需要你的非托管指针(vUnmanagedPublicKey)转换为托管指针(IntPtr的),这样元帅::复制可以使用它。 IntPtr的需要的本机指针作为参数之一给它的构造来执行该转换。
所以,你的全代码可能是这个样子:
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);
而不是使用编组-API更容易只脚管理的阵列:
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;