[英]Do the ISO C or C++ standards specify `const char *` should be a NULL terminated string?
[英]Managed C++ how to convert NOT Null terminated const char * to String ^
在我的本機+托管代碼項目中,我需要將const char *(不以null終止)轉換為托管字符串^。 當char *正確為null終止時,以下代碼可以很好地工作。 但是,當char *不為null終止時,它將返回瘋狂的字符串。
String^ STAK::CLRServerProxy::ToCLR(const char* str)
{
return msclr::interop::marshal_as<String^>(str);
}
有什么方法可以要求它將本機char *封送為僅前5個字符嗎? (此本地字符串始終為5個字符)。
謝謝,
String^ STAK::CLRServerProxy::ToCLR(const char* str)
{
return Marshal::PtrToStringAnsi((IntPtr) (char *) str, 5)
}
或者如果您想使其更加靈活
String^ STAK::CLRServerProxy::ToCLR(const char* str, size_t n)
{
return Marshal::PtrToStringAnsi((IntPtr) (char *) str, n)
}
通過傳遞5作為第二個參數進行調用
我寧願不創建副本
您必須創建一個副本,System :: String在結構上與const char *有很大不同。 Marshal類具有一個簡單的幫助程序方法,可以進行此轉換,您可以指定要轉換為多少字節,而無需正確終止的C字符串。 一個示例程序:
#include "stdafx.h"
using namespace System;
using namespace System::Diagnostics;
using namespace System::Runtime::InteropServices;
int main(array<System::String ^> ^args)
{
const char* str = "yada12345garbage...";
String^ s = Marshal::PtrToStringAnsi(IntPtr((void*)&str[4]), 5);
Debug::Assert(s == "12345");
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.