|
-
March 3rd, 2008, 03:58 AM
#1
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;
}
-
March 4th, 2008, 09:16 AM
#2
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|