trouble using unmanaged c++ from c# using dllimport

Discussion in 'C#' started by alag20, Sep 7, 2010.

  1. alag20

    alag20 New Member

    Joined:
    Sep 7, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi guys,
    i am having trouble importing c++ unmanaged dll into C# [winform]. Can someone help?

    Basically i am just trying to create a safearray of strings in c++ and trying to send it to C#.


    Here is my c++ code.

    Code:
    extern "C" __declspec(dllexport) BOOL GetStringArr(SAFEARRAY* arr)
    {
    SAFEARRAY*    myArray;
      SAFEARRAYBOUND  rgsabound[1];
    
      rgsabound[0].lLbound = 0;
      rgsabound[0].cElements = 5;
    
      myArray = SafeArrayCreate(VT_BSTR, 1, rgsabound);
      VARIANT* pvData = (VARIANT*)(myArray->pvData);
    
      pvData[0].vt = VT_BSTR;
      pvData[0].bstrVal = SysAllocString(L"FirstString");
      pvData[1].vt = VT_BSTR;
      pvData[1].bstrVal = SysAllocString(L"SecondString");
      pvData[2].vt = VT_BSTR;
      pvData[2].bstrVal = SysAllocString(L"ThirdString");
      pvData[3].vt = VT_BSTR;
      pvData[3].bstrVal = SysAllocString(L"FourthString");
      pvData[4].vt = VT_BSTR;
      pvData[4].bstrVal = SysAllocString(L"FifthString");
    
      arr = myArray;
      return true;
    }
    
    Here is my c# code.

    [DllImport("MyData.dll", EntryPoint = "GetStringArr")]
    public static extern bool GetStringArr([MarshalAs(UnmanagedType.SafeArray)] out Array strServerList);



    i am getting exception when i call GetStringArr from C#. i am sure there is something silly i am doing. Can someone please help?



    Thanks in advance.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice