CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Sep 2010
    Posts
    1

    Post trouble using unmanaged c++ from c# using dllimport

    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.

    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.

  2. #2
    Join Date
    Apr 2004
    Location
    England, Europe
    Posts
    2,492

    Re: trouble using unmanaged c++ from c# using dllimport

    The first thing you need to do is to declare your C function as __stdcall.
    My hobby projects:
    www.rclsoftware.org.uk

Tags for this Thread

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