![]() |
#2
追梦人zmrghy2022-12-10 13:39
|
就想把wstring转成char* 网上找来了转换函数。

wstring转char*
#include <xstring>
#include <iostream>
#include <comdef.h>
using namespace std;
char* ws2s(const wstring& ws)
{
_bstr_t t = ws.c_str();
char* pchar = (char*)t;
string result = pchar;
char* charTmp = new char;
strcpy(charTmp,result.c_str());
pchar = NULL;
delete pchar;
return charTmp;
}
测试过了C++控制台程序 和 C++/CLR控制台程序 都没有问题。
移植到C++/CLR winForm窗口程序 引发异常,不知如何解决。
只有本站会员才能查看附件,请 登录
main.cpp 代码

#include "Form1.h"
using namespace WstrTochar;
[STAThread]
int main(cli::array<System::String^>^ args)
{
Application::EnableVisualStyles();
Application::Run(gcnew Form1()); //Form1是窗体的名称
return 0;
}
Form1.h代码

#pragma once
#include"transverter.h"
namespace WstrTochar {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
}
protected:
~Form1()
{
if (components)
{
delete components;
}
}
private:
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
void InitializeComponent(void)
{
this->components = gcnew System::ComponentModel::Container();
this->Size = System::Drawing::Size(300,300);
this->Text = L"Form1";
this->Padding = System::Windows::Forms::Padding(0);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
}
#pragma endregion
};
}
transverter.h代码

#pragma once
#include <xstring>
#include <iostream>
#include <comdef.h>
using namespace std;
char* ws2s(const wstring& ws)
{
_bstr_t t = ws.c_str();
char* pchar = (char*)t;
string result = pchar;
char* charTmp = new char;
strcpy(charTmp, result.c_str());
pchar = NULL;
delete pchar;
return charTmp;
}
项目文件
只有本站会员才能查看附件,请 登录
只有本站会员才能查看附件,请 登录
这样就可以运行了。。。
是第10行代码出了问题。
char* pchar = (char*)t;
请教 各位大神,这个问题如何解决呀!!!