简体   繁体   English

托管C ++如何将NOT Null终止的const char *转换为String ^

[英]Managed C++ how to convert NOT Null terminated const char * to String ^

In my Native + Managed code project, I need to convert a const char * (Not null terminated) to Managed String ^. 在我的本机+托管代码项目中,我需要将const char *(不以null终止)转换为托管字符串^。 Following code works well when the char * is properly null terminated. 当char *正确为null终止时,以下代码可以很好地工作。 However it returns crazy strings when the char * is not null terminated. 但是,当char *不为null终止时,它将返回疯狂的字符串。

String^ STAK::CLRServerProxy::ToCLR(const char* str)
{
    return msclr::interop::marshal_as<String^>(str);    
}

Is there a way I can ask it to marshal this native char * to only first 5 characters ? 有什么方法可以要求它将本机char *封送为仅前5个字符吗? (This native string is always 5 chars long) (此本地字符串始终为5个字符)。

Thank you, 谢谢,

String^ STAK::CLRServerProxy::ToCLR(const char* str)
{
    return Marshal::PtrToStringAnsi((IntPtr) (char *) str, 5)
}

or if you want to make it more flexible 或者如果您想使其更加灵活

String^ STAK::CLRServerProxy::ToCLR(const char* str, size_t n)
{
    return Marshal::PtrToStringAnsi((IntPtr) (char *) str, n)
}

Calling by passing 5 as the 2nd param 通过传递5作为第二个参数进行调用

I would prefer not creating a copy 我宁愿不创建副本

You have to create a copy, System::String is structurally very different from const char*. 您必须创建一个副本,System :: String在结构上与const char *有很大不同。 The Marshal class has a simple helper method that makes this conversion, you can specify how many bytes to convert to you don't need a properly terminated C-string. Marshal类具有一个简单的帮助程序方法,可以进行此转换,您可以指定要转换为多少字节,而无需正确终止的C字符串。 An example program: 一个示例程序:

#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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM