5
.NET 프로젝트 내에 관리되지 않는 C++ 코드를 래핑합니다. 이를 위해 System::String
을 char*
에 저장된 UTF8 바이트로 변환해야합니다..NET System :: 문자열을 char로 저장된 UTF8-bytes에 저장합니다.
이것이 최선이거나 올바른 방법인지 확신 할 수 없으며 누군가가 살펴보고 의견을 제시 할 수 있다면 감사하겠습니다.
감사합니다,
/데이비드
// Copy into blank VisualStudio C++/CLR command line solution.
#include "stdafx.h"
#include <stdio.h>
using namespace System;
using namespace System::Text;
using namespace System::Runtime::InteropServices;
// Test for calling with char* argument.
void MyTest(const char* buffer)
{
printf_s("%s\n", buffer);
return;
}
int main()
{
// Create a UTF-8 encoding.
UTF8Encoding^ utf8 = gcnew UTF8Encoding;
// A Unicode string with two characters outside an 8-bit code range.
String^ unicodeString = L"This unicode string contains two characters with codes outside an 8-bit code range, Pi (\u03a0) and Sigma (\u03a3).";
Console::WriteLine(unicodeString);
// Encode the string.
array<Byte>^encodedBytes = utf8->GetBytes(unicodeString);
// Get pointer to unmanaged char array
int size = Marshal::SizeOf(encodedBytes[0]) * encodedBytes->Length;
IntPtr pnt = Marshal::AllocHGlobal(size);
Marshal::Copy(encodedBytes, 0, pnt, encodedBytes->Length);
// Ugly, but necessary?
char *charPnt= (char *)pnt.ToPointer();
MyTest(charPnt);
Marshal::FreeHGlobal(pnt);
}
매우 좋았습니다. 설명해 주셔서 감사합니다. –
이 예제에서는'pinnedBytes'가 어떻게 0 종결자를 얻는 지 보지 못합니다. 이것을 보장하는 마술이 있습니까? 아니면 독자를위한 운동으로 남았습니까? – StilesCrisis
@StilesCrisis oops, 네 말이 맞아, 나는 OP가 자신의 char 포인터를 printf % s에 전달했음을 간과 했음에 틀림 없다. 실제로 고정 된 바이트 뒤에 0 바이트가옵니다. 따라서 어쨌든 작동 할 수 있습니다. 그러나이를 보장하는 규칙을 알지 못합니다. 나는 대답을 조정할 것이다. – Zarat