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

Threaded View

  1. #1
    Join Date
    May 2010
    Posts
    7

    Passing array from unmanaged to managed code

    Hi,
    I have task I believe many people implemented many times.

    The C++ application has to pass array of string to C# dll. To my surprise I have found very little about such stuff on the web.
    I am able to pass single string, but when I try to pass SAFEARRAY* everything stops to work.
    Please help.
    To simplify my code I have a function which just pass array, but doesn’t do anything with it.
    If I commented out Safearray from function call, it works and return that “105”.

    The problem with SAFEARRAY. Is it possible that dll expects some other format of array?

    //dll
    public interface IEffDpthClc
    {
    int SetCtArray(int NN, string[] CtFileArray);
    }

    public class EffDpthClcClass : IEffDpthClc
    {
    …..
    public int SetCtArray(int NN , string[] CtFileArray)
    {
    return 105; //just test. if I pass array it doesn't work.
    }


    }
    //////////////////////////////
    //C++MFC application

    HRESULT hr = CoInitialize(NULL);
    IEffDpthClcPtr pIEffDpthClc(__uuidof(EffDpthClcClass));
    SAFEARRAY *pSA;
    SAFEARRAYBOUND aDim[1];
    aDim[0].lLbound= 0;
    aDim[0].cElements=10;
    pSA= SafeArrayCreate(VT_VARIANT,1,aDim);
    if (pSA != NULL)

    {
    ConvertCArrayToSmartArr(pSA );
    int z =pIEffDpthClc->SetCtArray(NN, pSA,p);
    SafeArrayDestroy(pSA);
    }
    CoUninitialize();

    ……
    HRESULT CPlan::ConvertCArrayToSmartArr(SAFEARRAY *pSA)
    {

    USES_CONVERSION;
    char buffer[10];
    HRESULT hr= S_OK;

    long aLong[1];

    for (long i= 0; i< NN; i++)
    {
    VARIANT vOut;
    VariantInit(&vOut);
    vOut.vt= VT_BSTR
    ltoa(i,buffer,10); // convert long to ANSI string value
    vOut.bstrVal= ::SysAllocString(A2W(buffer)); aLong[0]= i; // set index value
    if (hr= SafeArrayPutElement(pSA, aLong, &vOut))
    { // "correctly" copies VARIANT
    VariantClear(&vOut); // release BSTR from memory on error
    SafeArrayDestroy(pSA); // does a deep destroy on error
    return hr;
    }
    VariantClear(&vOut); // does a deep destroy of source VARIANT
    }

    }
    Thanks a lot. I have strglled with that stuff almost two workdays. Please help.
    Last edited by LenaKr; February 10th, 2012 at 05:20 PM.

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