배열 ^ to Unsigned char* :: Marshall Class- Interop 문제
-
06-07-2019 - |
문제
배열 <byte>^를 서명되지 않은 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;
제휴하지 않습니다 StackOverflow