CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Jan 2001
    Location
    Singapore
    Posts
    200

    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;
    }

  2. #2
    Join Date
    Nov 2002
    Location
    .NET 3.5 VS2008
    Posts
    1,039

    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
  •  





Click Here to Expand Forum to Full Width

Featured