【发布时间】:2018-03-19 22:45:25
【问题描述】:
我正在使用带有C# 和C++ 代码的C++ cli 解决方案。
当我尝试将 System::String 转换为 std::string 时,每次运行都会出现以下运行时异常:
ucrtbased.dll!00007ffd9902b9b0() Unknown
ucrtbased.dll!00007ffd9902eac5() Unknown
MyApp.dll!operator delete(void * block) Line 21 C++
[Managed to Native Transition]
MyApp.dll!std::_Deallocate(void* _Ptr, unsigned __int64 _Count, unsigned __int64 _Sz) Line 133 C++
MyApp.dll!std::allocator<char>::deallocate(char* _Ptr, unsigned __int64 _Count) Line 721 C++
MyApp.dll!std::_Wrap_alloc<std::allocator<char> >::deallocate(char* _Ptr, unsigned __int64 _Count) Line 988 C++
MyApp.dll!std::basic_string<char,std::char_traits<char>,std::allocator<char> >::_Tidy(bool _Built, unsigned __int64 _Newsize) Line 2260 C++
MyApp.dll!std::basic_string<char,std::char_traits<char>,std::allocator<char> >::=(std::basic_string<char,std::char_traits<char>,std::allocator<char> >& _Right) Line 934 C++
MyApp.dll!MyApp::DoStuff(System::String^ input) Line 59 C++
或者当我在没有调试器的情况下运行时:
我的代码,我尝试了两个选项,都导致同样的崩溃:
选项 1
void MyApp::DoStuff(System::String^ input) {
msclr::interop::marshal_context context;
std::string converted = context.marshal_as<const char*>(LicenseOEM);
}
选项 2
std::string SystemToStd(System::String^ sys) {
int len = sys->Length;
char* buff = (char*)malloc((len + 1) * sizeof(char));
for (int i = 0; i < sys->Length; i++) {
buff[i] = sys[i];
}
buff[len] = '\0';
std::string str = std::string(buff, len);
free(buff);
return str;
}
void MyApp::DoStuff(System::String^ input) {
std::string converted = SystemToStd(LicenseOEM);
}
【问题讨论】:
-
不应标记为 C++。 C++/CLI 是 ECMA-372 下的独立语言。 C++/CLI(与 C++ 相比)不幸地被命名为 JavaScript(与 Java 相比)。
-
好吧,考虑到差异,我的堆栈有 C++ 代码,所以不能与这个标签相差那么远。
标签: c++ c++-cli clr marshalling stdstring