微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

.net – 如何将System :: String ^转换为std :: string?

所以我在clr中工作,在visual c中创建.net dll.

我这样的代码

static bool InitFile(System::String^ fileName,System::String^ container)
{
    return enc.InitFile(std::string(fileName),std::string(container));
}

有编码器,normaly resives std :: string.但是如果我从std :: string和C2440中删除通常相同的参数,那么编译器(visual studio)会给出C2664错误. VS告诉我它无法将System :: String ^转换为std :: string.

所以我很伤心……我该怎么做才能将System :: String ^变成std :: string?

更新:

现在有了你的帮助,我有了这样的代码

#include <msclr\marshal.h>
#include <stdlib.h>
#include <string.h>
using namespace msclr::interop;
namespace NsstW
{
  public ref class CFEW
  {
 public:
     CFEW() {}

     static System::String^ echo(System::String^ stringToReturn)
    {
        return stringToReturn;  
    }

     static bool InitFile(System::String^ fileName,System::String^ container)
    {   
        std::string sys_fileName = marshal_as<std::string>(fileName);;
        std::string sys_container = marshal_as<std::string>(container);;
        return enc.InitFile(sys_fileName,sys_container);
    }
...

但是当我尝试编译时,它给了我C4996

错误C4996:’msclr :: interop :: error_reporting_helper< _To_Type,_From_Type> :: marshal_as’:库不支持此转换,或者不包括此转换所需的头文件.有关添加自己的编组方法的信息,请参阅“如何:扩展封送库”的文档.

该怎么办?

解决方法

如果您使用的是VS2008或更新版本,则可以使用 automatic marshaling added to C++非常简单地执行此操作.例如,您可以通过 marshal_as将System :: String ^转换为std :: string:
System::String^ clrstring = "CLR string";
std::string stdString = marshal_as<std::string>(clrstring);

这与用于P / Invoke调用的编组相同.

原文地址:https://www.jb51.cc/c/117434.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐