所以我在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调用的编组相同.