Elroy
Elroy

Reputation: 167

Passing a const char* character string from unmanaged to managed

I have two communicating components - one managed, the other unmanaged. The managed needs to retrieve a character string from the unmanaged implementation (the same string or just a copy). I tried the following code.

// Unmanaged code
const char* GetTestName(Test* test)
{
    return test->getName();
}

// Managed wrapper
[DllImport(DllName, EntryPoint = "GetTestName")]
public static extern IntPtr GetTestName(IntPtr testObj);

// API Invocation
IntPtr testName = GetTestName(test);
string testStr = Marshal.PtrToStringAuto(testName);

But, the value of testStr is not what is expected. Does anyone know what I'm doing wrong here? Any suggestions would be really helpful.

Upvotes: 1

Views: 3274

Answers (2)

Moudis
Moudis

Reputation: 86

I'd suggest this, instead:

[DllImport(DllName, EntryPoint = "EntryPoint")]
[MarshalAs(UnmanagedType.LPStr)]
public static extern StringBuilder GetTestName(IntPtr testObj);

UnmanagedType.LPStr works with strings and System.Text.StringBuilder, and perhaps others (I only ever used those two). I've found StringBuilder to work more consistantly, though.

See this MSDN article for further information on the various string marshalling options.

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 941635

You're close but you have to use PtrToStringAnsi(). Auto uses the system default which will be Unicode.

Upvotes: 1

Related Questions