I have a problem that can be demonstrated with a few small changed to the Example \csharp\extend in SWIG 2.0.12

I am running VS 2012, Windows 8 x64.

Steps to reproduce:
Replace Employee::getTitle with:
virtual std::wstring getTitle() { return L"Base"; }

Add this to the .i file:
%include "std_wstring.i"

Replace this line:
std::cout << "  " << (*i)->getTitle() << std::endl;
with this:
std::wcout << "  " << (*i)->getTitle() << std::endl;

Add this override to the C# CEO class:
public override string getTitle()
    return "CEO";

The example no longer prints out the CEO's title because it is garbage (Chinese characters likely).

The problem is in this SWIG generated code:
std::wstring SwigDirector_Manager::getTitle() {
  std::wstring c_result ;
  wchar_t * jresult = 0 ;
  if (!swig_callbackgetTitle) {
    return Employee::getTitle();
  } else {
    jresult = (wchar_t *) swig_callbackgetTitle();
    if (!jresult) {
      SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentNullException, "null wstring", 0);
      return c_result;
  return c_result;

The line that reads:
jresult = (wchar_t *) swig_callbackgetTitle();

Is casting a 'char *' returned by .NET to a wchar_t *

Does anyone have any ideas how I can fix this with a typemap or some such thing?

I tried adding this to the .i file:
    outattributes="[return: MarshalAs(UnmanagedType.LPWStr)]") std::wstring "String"

But that only affects these functions:
[DllImport("example", EntryPoint="CSharp_Employee_getTitle")]
[return: MarshalAs(UnmanagedType.LPWStr)]
public static extern String Employee_getTitle(HandleRef jarg1);

[DllImport("example", EntryPoint="CSharp_Employee_getTitleSwigExplicitEmployee")]
[return: MarshalAs(UnmanagedType.LPWStr)]
public static extern String Employee_getTitleSwigExplicitEmployee(HandleRef jarg1);

Not the one that is called, which is:
private String SwigDirectorgetTitle()

of the Manager class.


Andrew Ward.