The variable filepath which is a string contains the value Música. I have the following code:
wstring fp(filepath.length(), L' ');
copy(filepath.begin(), filepath.end(), fp.begin());
fp then contains the value M?sica. How do I convert filepath to fp without losing the encoding for the ú character?
Use the function MultiByteToWideChar.
Sample code:
std::string toStdString(const std::wstring& s, UINT32 codePage)
{
unsigned int bufferSize = (unsigned int)s.length()+1;
char* pBuffer = new char[bufferSize];
memset(pBuffer, 0, bufferSize);
WideCharToMultiByte(codePage, 0, s.c_str(), (int)s.length(), pBuffer, bufferSize, NULL, NULL);
std::string retVal = pBuffer;
delete[] pBuffer;
return retVal;
}
std::wstring toStdWString(const std::string& s, UINT32 codePage)
{
unsigned int bufferSize = (unsigned int)s.length()+1;
WCHAR* pBuffer = new WCHAR[bufferSize];
memset(pBuffer, 0, bufferSize*sizeof(WCHAR));
MultiByteToWideChar(codePage, 0, s.c_str(), (int)s.length(), pBuffer, bufferSize);
std::wstring retVal = pBuffer;
delete[] pBuffer;
return retVal;
}
Since you are using MFC, you have access to the ATL String Conversion Macros.
This greatly simplifies the conversion vs. using MultiByteToWideChar. Assuming that filepath is encoded in your system's default code page, this should do the trick:
CA2W wideFilepath(filepath.c_str());
wstring fp(static_cast<const wchar_t*>(wideFilepath));
If filepath is not in your system's default code page (let's say it's in UTF-8), then you can specify the encoding to convert from:
CA2W wideFilepath(filepath.c_str(), CP_UTF8);
wstring fp(static_cast<const wchar_t*>(wideFilepath));
To convert the other way, from std::wstring to std::string, you would do this:
// Convert from wide (UTF-16) to UTF-8
CW2A utf8Filepath(fp.c_str(), CP_UTF8);
string utf8Fp(static_cast<const char*>(utf8Filepath));
// Or, convert from wide (UTF-16) to your system's default code page.
CW2A narrowFilepath(fp.c_str(), CP_UTF8);
string narrowFp(static_cast<const char*>(narrowFilepath));
Related
http://postimg.org/image/btd4u4esx/
Hi,
This is the output image(black keyboard with white background) of a code that i modified from one of android samples. I want to take byte data from java file and send it to cpp using jni as unsigned character and and i am trying to display the video frames i receive using open cv mat.
JAVA CODE:
native int Fibonacci( byte[] n,int width, int height );
static {
System.loadLibrary( "CopyofHDRViewFinder" );
}
#Override
public void run() {
// y = 0.299*r + 0.587*g + 0.114*b
Log.v(TAG, "enter in imageSaver! Format is: " + mImage.getFormat());
ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
int heigth=mImage.getHeight();
int width=mImage.getWidth();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
int a=Fibonacci(bytes,width,heigth);
int pixelsize=mImage.getWidth()*mImage.getHeight();
System.out.println("framewidth:"+mImage.getWidth());
System.out.println("frameheight:"+mImage.getHeight());
System.out.println("totalnumberofpixels:"+pixelsize);
System.out.println("lastpixelvalue:"+a);
then the CPP code:(jni)
JNIEXPORT jint JNICALL Java_com_example_android_hdrviewfinder_HdrViewfinderActivity3_00024ImageSaver_Fibonacci
(JNIEnv *env, jobject obj, jbyteArray array, jint width, jint height)
{
i=i+1;
int len = env->GetArrayLength (array);
unsigned char* img = new unsigned char[len];
env->GetByteArrayRegion (array, 0, len-1, reinterpret_cast<jbyte*>(img));
const cv::Mat hdrimg(height,width, CV_8UC1, img);
char buffer[50];
int ab=sprintf(buffer,"/storage/emulated/0/Android/IMAGE%d.jpg",i);
cv::imwrite(buffer, hdrimg);
/*cv::namedWindow("HDRImage");
cv::imshow("HDRImage", hdrimg);
cv::waitKey(0);*/
printf("\n %d", width);
printf("\n %d", height);
int a;
for(int i=0;i<width*height;i++)
{
a=(int)img[i];
}
int c=width*height;
return a;
}
This returns proper pixel values from 0 to 255. my issue is not that. when i check the image it looks blurry and totally horrible, but still i cant deduce that its a keyboard slightly. Anyone has seen similar results? Help, if you can..
I have a wstring that I assign in the following function. I pull out of the string with the .substr method with the start and length parameters. But once I do a substr, how do I get the result ultimately into a TCHAR that the function can return (and assign as one of its parameters):
TCHAR *Mid(TCHAR *dest, TCHAR *source, size_t start, size_t num)
{
wstring sSource(s);
// this line won't compile, unable to fix. How to get from subst to TCHAR?
dest = sSource.substr(start, num);
return dest;
}
Thanks!
EDIT: Perhaps this?
{
wstring wSource(source);
wstring wTemp;
wTemp = wSource.substr(start, num);
_tcscpy(dest,wTemp.c_str());
return dest;
}
I would like to convert a CLSID to a *char in c++ so I can display it in a text box. I am new to c++ so please make this as simple a s possible.
Thanks
C'ish solution:
/* 128 bit GUID to human-readable string */
char * guid_to_str(const GUID * id, char * out) {
int i;
char * ret = out;
out += sprintf(out, "%.8lX-%.4hX-%.4hX-", id->Data1, id->Data2, id->Data3);
for (i = 0; i < sizeof(id->Data4); ++i) {
out += sprintf(out, "%.2hhX", id->Data4[i]);
if (i == 1) *(out++) = '-';
}
return ret;
}
This assumes the output buffer has been already allocated, and should be of a size of 37 bytes (including the null terminating character).
The output is of the form "75B22630-668E-11CF-A6D9-00AA0062CE6C"
Usage example:
GUID g;
char buffer[37];
std::cout << guid_to_str(&g, buffer);
Note:
This code exists because I had to implement GUID parsing under Linux, otherwise I would have used the Windows API function StringFromCLSID mentioned by #krowe.
Here is a great example for converting GUID to string and vice versa that I am using in my projects:
std::string guidToString(GUID guid) {
std::array<char,40> output;
snprintf(output.data(), output.size(), "{%08X-%04hX-%04hX-%02X%02X-%02X%02X%02X%02X%02X%02X}", guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
return std::string(output.data());
}
GUID stringToGUID(const std::string& guid) {
GUID output;
const auto ret = sscanf(guid.c_str(), "{%8X-%4hX-%4hX-%2hX%2hX-%2hX%2hX%2hX%2hX%2hX%2hX}", &output.Data1, &output.Data2, &output.Data3, &output.Data4[0], &output.Data4[1], &output.Data4[2], &output.Data4[3], &output.Data4[4], &output.Data4[5], &output.Data4[6], &output.Data4[7]);
if (ret != 11)
throw std::logic_error("Unvalid GUID, format should be {00000000-0000-0000-0000-000000000000}");
return output;
}
In the example, it firsts uses char* before converting to string so this is exactly what you are looking for in an efficient way.
The Windows API has a function for this:
CLSID clsid;
HRESULT hr = CLSIDFromProgID ((OLESTR "Adobe.SVGCtl.3"),&clsid);
// Get class id as string
LPOLESTR className;
hr = StringFromCLSID(clsid, &className);
// convert to CString
CString c = (char *) (_bstr_t) className;
// then release the memory used by the class name
CoTaskMemFree(className);
// Now c is ready to use
A CLSID is the same as a UUID, so you can use the UuidToString() function
http://msdn.microsoft.com/en-us/library/windows/desktop/aa379352(v=vs.85).aspx
I use the following code, but does not get the right version string of jemalloc.
size_t size = 1000;
char *ptr = (char *) malloc(size);
mallctl("version", ptr, &size, NULL, 0);
I just got a 4-bits size string, and I printed it out found not the version string.
I think the problem is the version string is a const char*. But if I call with a const char*, what size should I fill in?
You should fill in the size of a const char *, of course.
The "version" parameter is a const char *, which is four bytes on your platform. This function doesn't get the version string but actually gets a pointer to the version string. You don't need to allocate space for the version, just a pointer. Here's working example code:
#include "stdio.h"
#include "jemalloc/jemalloc.h"
int main(void)
{
const char *j;
size_t s = sizeof(j);
mallctl("version", &j, &s, NULL, 0);
printf("%s\n", j);
}
Can someone please post a simple code that would convert,
System::String^
To,
C++ std::string
I.e., I just want to assign the value of,
String^ originalString;
To,
std::string newString;
Don't roll your own, use these handy (and extensible) wrappers provided by Microsoft.
For example:
#include <msclr\marshal_cppstd.h>
System::String^ managed = "test";
std::string unmanaged = msclr::interop::marshal_as<std::string>(managed);
You can easily do this as follows
#include <msclr/marshal_cppstd.h>
System::String^ xyz="Hi boys";
std::string converted_xyz=msclr::interop::marshal_as< std::string >( xyz);
Check out System::Runtime::InteropServices::Marshal::StringToCoTaskMemUni() and its friends.
Sorry can't post code now; I don't have VS on this machine to check it compiles before posting.
This worked for me:
#include <stdlib.h>
#include <string.h>
#include <msclr\marshal_cppstd.h>
//..
using namespace msclr::interop;
//..
System::String^ clrString = (TextoDeBoton);
std::string stdString = marshal_as<std::string>(clrString); //String^ to std
//System::String^ myString = marshal_as<System::String^>(MyBasicStirng); //std to String^
prueba.CopyInfo(stdString); //MyMethod
//..
//Where: String^ = TextoDeBoton;
//and stdString is a "normal" string;
Here are some conversion routines I wrote many years ago for a c++/cli project, they should still work.
void StringToStlWString ( System::String const^ s, std::wstring& os)
{
String^ string = const_cast<String^>(s);
const wchar_t* chars = reinterpret_cast<const wchar_t*>((Marshal::StringToHGlobalUni(string)).ToPointer());
os = chars;
Marshal::FreeHGlobal(IntPtr((void*)chars));
}
System::String^ StlWStringToString (std::wstring const& os) {
String^ str = gcnew String(os.c_str());
//String^ str = gcnew String("");
return str;
}
System::String^ WPtrToString(wchar_t const* pData, int length) {
if (length == 0) {
//use null termination
length = wcslen(pData);
if (length == 0) {
System::String^ ret = "";
return ret;
}
}
System::IntPtr bfr = System::IntPtr(const_cast<wchar_t*>(pData));
System::String^ ret = System::Runtime::InteropServices::Marshal::PtrToStringUni(bfr, length);
return ret;
}
void Utf8ToStlWString(char const* pUtfString, std::wstring& stlString) {
//wchar_t* pString;
MAKE_WIDEPTR_FROMUTF8(pString, pUtfString);
stlString = pString;
}
void Utf8ToStlWStringN(char const* pUtfString, std::wstring& stlString, ULONG length) {
//wchar_t* pString;
MAKE_WIDEPTR_FROMUTF8N(pString, pUtfString, length);
stlString = pString;
}
I found an easy way to get a std::string from a String^ is to use sprintf().
char cStr[50] = { 0 };
String^ clrString = "Hello";
if (clrString->Length < sizeof(cStr))
sprintf(cStr, "%s", clrString);
std::string stlString(cStr);
No need to call the Marshal functions!
UPDATE Thanks to Eric, I've modified the sample code to check for the size of the input string to prevent buffer overflow.
I spent hours trying to convert a windows form listbox ToString value to a standard string so that I could use it with fstream to output to a txt file. My Visual Studio didn't come with marshal header files which several answers I found said to use. After so much trial and error I finally found a solution to the problem that just uses System::Runtime::InteropServices:
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));
}
//this is the code to use the function:
scheduleBox->SetSelected(0,true);
string a = "test";
String ^ c = gcnew String(scheduleBox->SelectedItem->ToString());
MarshalString(c, a);
filestream << a;
And here is the MSDN page with the example:
http://msdn.microsoft.com/en-us/library/1b4az623(v=vs.80).aspx
I know it's a pretty simple solution but this took me HOURS of troubleshooting and visiting several forums to finally find something that worked.
C# uses the UTF16 format for its strings.
So, besides just converting the types, you should also be conscious about the string's actual format.
When compiling for Multi-byte Character set Visual Studio and the Win API assumes UTF8 (Actually windows encoding which is Windows-28591 ).
When compiling for Unicode Character set Visual studio and the Win API assume UTF16.
So, you must convert the string from UTF16 to UTF8 format as well, and not just convert to std::string.
This will become necessary when working with multi-character formats like some non-latin languages.
The idea is to decide that std::wstring always represents UTF16.
And std::string always represents UTF8.
This isn't enforced by the compiler, it's more of a good policy to have.
#include "stdafx.h"
#include <string>
#include <codecvt>
#include <msclr\marshal_cppstd.h>
using namespace System;
int main(array<System::String ^> ^args)
{
System::String^ managedString = "test";
msclr::interop::marshal_context context;
//Actual format is UTF16, so represent as wstring
std::wstring utf16NativeString = context.marshal_as<std::wstring>(managedString);
//C++11 format converter
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> convert;
//convert to UTF8 and std::string
std::string utf8NativeString = convert.to_bytes(utf16NativeString);
return 0;
}
Or have it in a more compact syntax:
int main(array<System::String ^> ^args)
{
System::String^ managedString = "test";
msclr::interop::marshal_context context;
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> convert;
std::string utf8NativeString = convert.to_bytes(context.marshal_as<std::wstring>(managedString));
return 0;
}
I like to stay away from the marshaller.
Using CString newString(originalString);
Seems much cleaner and faster to me. No need to worry about creating and deleting a context.
// I used VS2012 to write below code-- convert_system_string to Standard_Sting
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace System;
using namespace Runtime::InteropServices;
void MarshalString ( String^ s, std::string& outputstring )
{
const char* kPtoC = (const char*) (Marshal::StringToHGlobalAnsi(s)).ToPointer();
outputstring = kPtoC;
Marshal::FreeHGlobal(IntPtr((void*)kPtoC));
}
int _tmain(int argc, _TCHAR* argv[])
{
std::string strNativeString;
String ^ strManagedString = "Temp";
MarshalString(strManagedString, strNativeString);
std::cout << strNativeString << std::endl;
return 0;
}
For me, I was getting an error with some of these messages. I have an std::string. To convert it to String^, I had to do the following String^ sysString = gcnew String(stdStr.c_str()); where sysString is a System::String^ and stdStr is an std::string. Hope this helps someone
You may have to #include <string> for this to work