2010-08-21 184 views
6

所以我在clr工作,在visual C++中创建.net dll。如何将System :: String ^转换为std :: string?

我TRU这样的代码:

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

具有编码器,其normaly resives的std :: string。但在这里编译器(Visual Studio)给我C2664错误,如果我从std :: string和通常相同的C2440去掉参数。 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 ::互操作:: error_reporting_helper < _To_Type,_From_Type> :: marshal_as':库不支持此转换,或不包含此转换所需的头文件。请参阅“如何:扩展编组库”文档以添加自己的编组方法。

该怎么办?

+4

你已经包含'msclr \ marshal.h'。试试'msclr \ marshal_cppstd.h'。 – 2010-08-21 23:14:58

+0

@Chris Schmich:谢谢 - 现在它编译完美=) – Rella 2010-08-21 23:18:25

回答

6

如果您使用的是VS2008或更新的版本,您可以使用automatic marshaling added to C++进行简单操作。例如,您可以通过marshal_asSystem::String^转换为std::string

System::String^ clrString = "CLR string"; 
std::string stdString = marshal_as<std::string>(clrString); 

这是用于P中的相同编组/ Invoke调用。

+0

我喜欢主意,但如何在我的代码中声明marshal_as?在哪里和我写什么来声明它(摆脱错误C2065),我使用VS2008 – Rella 2010-08-21 23:03:51

+1

要从'System :: String ^'转到'std :: string',你需要'#include '声明'marshal_as'。 – 2010-08-21 23:06:59

+0

当我尝试#include 它给我致命错误C1083 ...所以我编辑了代码并将其发布在问题中(我使用他们在MS MSDN示例中使用的内容)...你可以看看它请。 – Rella 2010-08-21 23:14:01

4

从文章How to convert System::String^ to std::string or std::wstring MSDN上:

void MarshalString (String^s, string& os) 
{ 
    using namespace Runtime::InteropServices; 
    const char* chars = 
     (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer(); 
    os = chars; 
    Marshal::FreeHGlobal(IntPtr((void*)chars)); 
} 

用法:

std::string a; 
System::String^ yourString = gcnew System::String("Foo"); 
MarshalString(yourString, a); 
std::cout << a << std::endl; // Prints "Foo" 
3

您需要包括marshal_cppstd.h将字符串转换^到的std :: string。

你没有提到你是否关心非ASCII字符。 如果你需要unicode(如果没有,为什么不!),有一个marshal_as返回一个std :: wstring。

如果你使用的是utf8,你将不得不推出自己的。你可以使用一个简单的循环:

System::String^ s = ...; 
std::string utf8; 
for each(System::Char c in s) 
    // append encoding of c to "utf8"; 
相关问题