JStringToCString: Any Takers?
Mohan Embar
gnustuff@thisiscool.com
Tue Jul 1 18:16:00 GMT 2003
Hi People,
>Only mingw32-specific files are affected by this. Of
>particular interest are the helper functions and classes
>I've added to include/win32.h. The Posix folks might
>benefit from JStringToCString and JvGetStringUTF too.
In my cleanup / factoring / enhancements, I am
declaring /defining the class and helper function
in win32.h / win32.cc shown at the end of this post.
Here is a typical usage:
------------------------------------8<--------------------------------------------
jboolean
java::io::File::performMkdir (void)
{
jvwin32::JStringToCString cpath(path);
return (CreateDirectory(cpath, NULL)) ? true : false;
}
------------------------------------8<--------------------------------------------
Would the non-Win32 folks find these useful too? Yes,
I know the names are probably wrong and the hardcoded
500 isn't pretty, but do you want these or not? If not, I'll
just keep them in Win32-land.
If I don't here from someone soon about this, I'll just keep
these where they are.
-- Mohan
http://www.thisiscool.com/
http://www.animalsong.org/
win32.h:
------------------------------------8<--------------------------------------------
/* Useful helper classes and methods. We use a namespace
to avoid any global collisions. */
namespace jvwin32
{
/* Converts a jstring to a temporary char*. */
class JStringToCString
{
public:
JStringToCString(jstring jstr);
~JStringToCString();
// Accessors
operator const char*() const {return buf_;}
const char* buf() const {return buf_;}
char* buf() {return buf_;}
private:
char* buf_;
char stackbuf_[500];
bool heapAllocated_;
};
/* Gets the whole string into buf and null-terminates it. */
extern int
JvGetStringUTF(jstring str, char* buf);
}
------------------------------------8<--------------------------------------------
win32.cc:
------------------------------------8<--------------------------------------------
// Helper classes and methods implementation
namespace jvwin32
{
// class JStringToCString
JStringToCString::JStringToCString (jstring jstr):
buf_(0),
heapAllocated_(false)
{
if (!jstr) return;
jsize len = JvGetStringUTFLength(jstr);
if (len < jsize(sizeof(stackbuf_)-1))
{
buf_ = stackbuf_;
}
else
{
buf_ = (char*) _Jv_Malloc (len+1);
heapAllocated_ = true;
}
JvGetStringUTF (jstr, buf_);
}
JStringToCString::~JStringToCString ()
{
if (heapAllocated_)
_Jv_Free (buf_);
}
int
JvGetStringUTF(jstring str, char* buf)
{
jsize len = JvGetStringUTFRegion (str, 0, str->length(), buf);
buf[len] = '\0';
return len;
}
}
------------------------------------8<--------------------------------------------
More information about the Java-patches
mailing list