質問

I am trying to convert const char * to LPTSTR. But i do not want to use USES_CONVERSION to perform that.

The following is the code i used to convert using USES_CONVERSION. Is there a way to convert using sprintf or tcscpy, etc..?

USES_CONVERSION;
jstring JavaStringVal = (some value passed from other function);
const char *constCharStr = env->GetStringUTFChars(JavaStringVal, 0);    
LPTSTR lpwstrVal = CA2T(constCharStr); //I do not want to use the function CA2T..
役に立ちましたか?

解決

LPTSTR has two modes:

An LPWSTR if UNICODE is defined, an LPSTR otherwise.

#ifdef UNICODE
    typedef LPWSTR LPTSTR;
#else
    typedef LPSTR LPTSTR;
#endif

or by the other way:

LPTSTR is wchar_t* or char* depending on _UNICODE

if your LPTSTR is non-unicode:

according to MSDN Full MS-DTYP IDL documentation, LPSTR is a typedef of char *:

typedef char* PSTR, *LPSTR;

so you can try this:

const char *ch = "some chars ...";
LPSTR lpstr = const_cast<LPSTR>(ch);

他のヒント

USES_CONVERSION and related macros are the easiest way to do it. Why not use them? But you can always just check whether the UNICODE or _UNICODE macros are defined. If neither of them is defined, no conversion is necessary. If one of them is defined, you can use MultiByteToWideChar to perform the conversion.

Actually that's a silly thing to do. JNIEnv alreay has a method to get the characters as Unicode: JNIEnv::GetStringChars. So just check for the UNICODE and _UNICODE macros to find out which method to use:

#if defined(UNICODE) || defined(_UNICODE)
    LPTSTR lpszVal = env->GetStringChars(JavaStringVal, 0);
#else
    LPTSTR lpszVal = env->GetStringUTFChars(JavaStringVal, 0);
#endif

In fact, unless you want to pass the string to a method that expects a LPTSTR, you should just use the Unicode version only. Java strings are stored as Unicode internally, so you won't get the overhead of the conversion, plus Unicode strings are just better in general.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top