MasterMastic
MasterMastic

Reputation: 21306

Passing string from C++ to C++/CLI

I have in my C++/CLI project some native functions and a ref (managed) class that exposes them to a C# project.

One of the functions that it exposes returns a WCHAR* string (AKA LPWSTR / wchar_t*).
When I ran the C# program which prints it, all I could see is square symbols.

I've set a breakpoint at the native return statement and the debugger shows that the returned string is correct. Then I stepped over once and landed in the managed function (which has a WCHAR* variable that's set to the returned value), and somehow it shows those square symbols.

It seems like once the string enters the managed "section" it gets messed up.
I'd show my code but the issue happens before I even convert the WCHAR* string into System::String so it doesn't really matter.

Code sample as requested:

static String^ GetWindowTitle(IntPtr windowHandle)
{
    HWND hWnd = (HWND)windowHandle.ToPointer();
    LPWSTR nativeTitle = NativeGetWindowTitle(hWnd).get();
    String^ title = gcnew String(nativeTitle);

    return title;
}

Upvotes: 1

Views: 468

Answers (1)

David Heffernan
David Heffernan

Reputation: 613432

Looking at this line:

LPWSTR nativeTitle = NativeGetWindowTitle(hWnd).get();

it seems clear that nativeTitle points to memory owner by the temporary object returned by NativeGetWindowTitle(hWnd). But that temporary has gone by the time you pass nativeTitle.

According to the C++ standard:

Temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created.

Assuming that everything else that we cannot see, works correctly, you can fix your problem by making sure that the object returned by NativeGetWindowTitle(hWnd) lives beyond the gcnew statement.

Upvotes: 3

Related Questions