How to: Convert System::String to wchar_t* or char*
来源:互联网 发布:男士抗痘洗面奶知乎 编辑:程序博客网 时间:2024/05/16 17:37
在.net平台上使用c++/clr开发,经常会遇到这样一个问题:How to: Convert System::String to wchar_t* or char* ?
MSDN上的这篇文章会打消你的疑虑,告诉你一个转换途径。(简单的英文,恕不翻译)
You can use PtrToStringChars in Vcclr.h to convert
Example
// convert_string_to_wchar.cpp
// compile with: /clr
#include < stdio.h >
#include < stdlib.h >
#include < vcclr.h >
using namespace System;
int main() {
String ^str = "Hello";
// Pin memory so GC can't move it while native function is called
pin_ptr<const wchar_t> wch = PtrToStringChars(str);
printf_s("%S ", wch);
// Conversion to char* :
// Can just convert wchar_t* to char* using one of the
// conversion functions such as:
// WideCharToMultiByte()
// wcstombs_s()
// ... etc
size_t convertedChars = 0;
size_t sizeInBytes = ((str->Length + 1) * 2);
errno_t err = 0;
char *ch = (char *)malloc(sizeInBytes);
err = wcstombs_s(&convertedChars,
ch, sizeInBytes,
wch, sizeInBytes);
if (err != 0)
printf_s("wcstombs_s failed! ");
printf_s("%s ", ch);
}
// compile with: /clr
#include < stdio.h >
#include < stdlib.h >
#include < vcclr.h >
using namespace System;
int main() {
String ^str = "Hello";
// Pin memory so GC can't move it while native function is called
pin_ptr<const wchar_t> wch = PtrToStringChars(str);
printf_s("%S ", wch);
// Conversion to char* :
// Can just convert wchar_t* to char* using one of the
// conversion functions such as:
// WideCharToMultiByte()
// wcstombs_s()
// ... etc
size_t convertedChars = 0;
size_t sizeInBytes = ((str->Length + 1) * 2);
errno_t err = 0;
char *ch = (char *)malloc(sizeInBytes);
err = wcstombs_s(&convertedChars,
ch, sizeInBytes,
wch, sizeInBytes);
if (err != 0)
printf_s("wcstombs_s failed! ");
printf_s("%s ", ch);
}
Output:
HelloHello
- How to: Convert System::String to wchar_t* or char*
- How to convert wchar_t* to char*
- Convert Between char* string to wchar_t* string
- How to convert InputStream to String/convert char[] to String
- How to convert char array to String in Java
- Convert std::string to const char* or char*
- cannot convert wchar_t to const char*
- E2034 Cannot convert 'wchar_t *' to 'const char *'
- how to convert char to char []
- How to convert array<System::Byte> to char* in C++ CLR?
- How to convert string to Guid type.
- How to convert a String to DateTime
- How to convert QString to std::string?
- How to properly convert SecureString to String
- how to convert wstring to string
- wchar_t TO char & char TO wchar_t
- wchar_t TO char & char TO wchar_t
- char to wchar_t
- 关于DataList使用DropDownList的分页实现 技巧实例源码
- 无弹出框的验证
- 有人问“AppSettings和ConnectionStrings的区别”?
- 我的工作
- 利用struts框架实现URL地址映射配置的关键点
- How to: Convert System::String to wchar_t* or char*
- 什么是串口
- ADO.NET的最佳实践技巧
- 配置struts-config.xml连接数据库
- Struts的表单验证中
- web.config
- MVC与过滤器
- 如何将自定义的方法应用到DataGrid的绑定列上
- 提高网页打开速度的一些小技巧