> At ZNC we have an own string class CString, which is inherited from > std::string. > The goal is to use it as a just string in target languages. > > How to do that properly?
When you use a string class derived from std::string, the main problem tends to be that SWIG's built-in typemaps refer to std::string explicitly, but that's unnecessary. For some target languages (at least C# and Java) if you simply make a copy of the typemap with std::string changed to $*1_ltype, then you can %apply those typemaps to your derived class. For example, here are the corrected typemaps for Java: namespace std { // Changed lines are marked "//fixed" %typemap(in) const string & %{ if(!$input) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "String param cannot be null"); return $null; } const char *$1_pstr = (const char *)jenv->GetStringUTFChars($input, 0); if (!$1_pstr) return $null; $*1_ltype $1_str($1_pstr); //fixed $1 = &$1_str; jenv->ReleaseStringUTFChars($input, $1_pstr); %} %typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const string & %{ if(!$input) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "String param cannot be null"); return $null; } const char *$1_pstr = (const char *)jenv->GetStringUTFChars($input, 0); if (!$1_pstr) return $null; /* possible thread/reentrant code problem */ static $1_ltype $1_str; //fixed $1_str = $1_pstr; $result = &$1_str; jenv->ReleaseStringUTFChars($input, $1_pstr); %} } // namespace std Then you use %apply to support your custom string too: %apply std::string { CString } %apply std::string& { CString& } // [not supported in Java] %apply const std::string& { const CString& }