Sunday, April 5, 2015

Managed C++ String을 char*로 변환

// ManagedStr.cpp : main project file.
#include "stdafx.h"
#include <stdio.h>

using namespace System;
using namespace System::Runtime::InteropServices;

int main(array<System::String ^> ^args)
{
    // Create a managed string.
    String^ managedString = "Hello unmanaged world (from the managed world).";
    // Marshal the managed string to unmanaged memory.
    char* stringPointer = (char*)Marshal::StringToHGlobalAnsi(managedString).ToPointer();
    wchar_t* wstringPointer = (wchar_t*)Marshal::StringToHGlobalUni(managedString).ToPointer();
    printf("stringPointer = %s\n", stringPointer);
    wprintf(L"stringPointer = %s\n", wstringPointer);
    // Always free the unmanaged string.
    Marshal::FreeHGlobal(IntPtr(stringPointer));
    Marshal::FreeHGlobal(IntPtr(wstringPointer));
    getchar();
    return 0;
}

No comments:

Post a Comment