我想转换数组<字节> ^到unsigned char *。我试图解释我做了什么。我不知道如何继续前进。请告诉我正确的方法。我正在使用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是一个数字。但是如何将数据从vPublicKey复制到vUnmanagedPublicKey。

谢谢你 拉吉

有帮助吗?

解决方案

尝试用以下代码替换最后两行:

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

您已在非托管内存中分配了一个缓冲区以将密钥复制到,因此无需使用AllocHGlobal分配非托管内存。您只需将非托管指针(vUnmanagedPublicKey)转换为托管指针(IntPtr),以便Marshal :: Copy可以使用它。 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;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top