JNI character set conversion

xiaoxiao2021-03-06  60

When writing Java jni, the most headache is the leading problem of the character set. It is well known that the string of Java is stored in Unicode, and most of C / C is single-byte processing, which involves a conversion problem. The following is the conversion between the two functions to be between JString to Char *:

// Author Naven 2003 for Both Win32 and UNIX OS

/ / For easy use, there is no need to connect the library, and Win32 needs to write a double-byte MEMSET function.

#if Defined (_win32) || defined (__ win32__)

Wchar_t * mywmemset (wchar_t * _s, wchar_t _c, size_t _n)

{

Wchar_t * _su = _s;

For (; 0 <_n; _ su, --_ n)

* _Su = _C;

Return (_S);

}

#ENDIF

// Convert JAVA JString type to single-byte string

Size_t JStringToChars (Jnienv * ENV,

Const JString JSTR, Char * MBSTR, Const Size_t Mbslen

{

Const Jchar * JWSTR;

Wchar_t * wbuf = 0;

SIZE_T nsize = 0;

Jsize jlen = 0;

Register INT i = 0;

MEMSET (MBSTR, 0, MBSLEN);

IF (jstr == null) Return 0;

JWSTR = (* ENV) -> GetStringChars (ENV, JSTR, 0);

Jlen = (* ENV) -> GetStringLength (ENV, JSTR);

IF (Jlen <= 0) Return 0;

#if Defined (_win32) || defined (__ win32__)

WBUF = (wchar_t *) jwstr;

nsize = WCSTOMBS (MBSTR, WBUF, MBSLEN-1);

#ELSE

WBUF = (wchar_t *) Malloc ((Jlen 1) * sizeof (wchar_t));

MYWMEMSET (WBUF, (Wchar_T) 0, (SIZE_T) (Jlen 1));

For (i = 0; i

WBUF [i] = (wchar_t) jwstr [i];

nsize = WCSTOMBS (MBSTR, WBUF, MBSLEN-1);

Free (WBUF);

#ENDIF

IF (nsize> = 0 && nsize

MBSTR [nsize] = 0;

Return nsize;

}

// Convert a single-byte string into a jstring type that can be used in Java

Size_t charstojstring (jnienv * ENV,

Const Char * MBSTR, JString * JSTR)

{

JCHAR * JWSTR = 0;

WCHAR_T * WCSTR = 0;

SIZE_T SLEN = 0, nsize = 0;

Register INT i = 0;

IF (MBSTR! = NULL)

Slen = Strlen (MBSTR);

IF (MBSTR == Null || Slen <= 0) {

* JSTR = (* ENV) -> Newstringutf (ENV, "); RETURN 0;

}

WCSTR = (wchar_t *) Malloc (Slen 1) * sizeof (wchar_t));

MYWMEMSET (WCSTR, 0, SLEN 1);

nsize = MBSTOWCS (WCSTR, MBSTR, SLEN * 2);

JWSTR = (JCHAR *) WCSTR;

#if Defined (_win32) || defined (__ win32__)

#ELSE

For (i = 0; i <(int) nsize; i ) {

JWSTR [i] = jwstr [i * 2];

}

JWSTR [nsize] = 0;

#ENDIF

IF (nsize <= 0)

* JSTR = (* ENV) -> Newstringutf (ENV, "");

Else

* JSTR = (* ENV) -> Newstring (ENV, JWSTR, NSIZE);

Free (WCSTR);

Return nsize;

}

转载请注明原文地址:https://www.9cbs.com/read-109157.html

New Post(0)