Using DllImport to get string from unmanaged c++ dll
I need to call a unmanaged c++ function which returns a string from c#.
The code shown below (TestApp) works fine for TestDll1 where the GetStringFromDll() returns a char*.
However what should I do if the unmanaged c++ function returns CString/LPTSTR instead of char* (see TestDll2.cpp and TestDll3.cpp).
I tried using TestApp shown below for TestDll2.cpp and the ReceivedStr only contains the first character 'T' instead of the "Testing". Can anybody help?
// Sample program in c# to call unmanaged code
using System;
using System.Runtime.InteropServices;
class TestApp
{
[DllImport("TestDll1.dll")]
static extern void GetStringFromDll();
public static void Main()
{
string ReceivedStr = GetStringFromDll();
}
}
// TestDll1.cpp
// Written in unmanaged c++
__declspec(dllexport) char* GetStringFromDll()
{
static char* pszReturn;
pszReturn = "Testing";
return pszReturn;
}
// TestDll2.cpp
// Written in unmanaged c++
__declspec(dllexport) LPTSTR GetStringFromDll()
{
LPTSTR pszReturn;
pszReturn = _T("Testing");
return pszReturn;
}
// TestDll3.cpp
// Written in unmanaged c++
__declspec(dllexport) CString GetStringFromDll()
{
CString pszReturn;
pszReturn = "Testing";
return pszReturn;
}
Re: Using DllImport to get string from unmanaged c++ dll
Please use code tags next time!!!
Anyway...
in an non-Unicode build
LPTSTR is the same as char* so that's that.
CString is an MFC class and I don't think it can be marshalled by platform invoke directly. However the CString has an const char* operator so can use const char* or LPCTSTR as the return value for the unmanaged function.