Передача массива строк из Borland C ++ в C # - PullRequest
0 голосов
/ 02 мая 2019

Я хочу передать список строк адресов электронной почты из Borland C ++ в мою библиотеку C #.Ниже мой код стороны C #.Я мог бы сделать вызов метода PrintName (), и он работает.Теперь я хочу напечатать адреса электронной почты, но если я вызову функцию PrintEmails (), ничего не произойдет.Не могли бы вы подсказать, как я могу передать несколько адресов электронной почты в C # lib.

[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("4A686AB1-8425-43D9-BD89-B696BB5F6A18")]
public interface ITestConnector
{
    void PrintEmails(string[] emails);
    void PrintName(string name);
}


[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(ITestConnector))]
[Guid("7D818287-298A-41BF-A224-5EAC9C581BD0")]
public class TestConnector : ITestConnector
{
    public void PrintEmails(string[] emails)
    {
        System.IO.File.WriteAllLines(@"c:\temp\emails.txt", emails);
    }

    public void PrintName(string name)
    {
        System.IO.File.WriteAllText(@"c:\temp\name.txt", name);
    }
} 

Я импортировал файл TLB из библиотеки выше C # в RAD Studio, и мой код на C ++ выглядит следующим образом.

interface ITestConnector  : public IUnknown
{
public:
  virtual HRESULT STDMETHODCALLTYPE PrintEmails(LPSAFEARRAY* emails/*[in,out]*/) = 0; // [-1]
  virtual HRESULT STDMETHODCALLTYPE PrintName(WideString name/*[in]*/) = 0; // [-1]
};

TTestConnector *connector = new TTestConnector(this);

SAFEARRAYBOUND bounds[] = {{2, 0}}; //Array Contains 2 Elements starting from Index '0'
LPSAFEARRAY pSA = SafeArrayCreate(VT_VARIANT,1,bounds); //Create a one-dimensional SafeArray of variants
long lIndex[1];
VARIANT var;

lIndex[0] = 0; // index of the element being inserted in the array
var.vt = VT_BSTR; // type of the element being inserted
var.bstrVal = ::SysAllocStringLen( L"abc@xyz.com", 11 ); // the value of the element being inserted
HRESULT hr= SafeArrayPutElement(pSA, lIndex, &var); // insert the element

// repeat the insertion for one more element (at index 1)
lIndex[0] = 1;
var.vt = VT_BSTR;
var.bstrVal = ::SysAllocStringLen( L"pqr@xyz.com", 11 );
hr = SafeArrayPutElement(pSA, lIndex, &var);

connector->PrintEmails(pSA);
delete connector;

1 Ответ

0 голосов
/ 03 мая 2019

Ниже C ++ код работал в моем случае.

SAFEARRAYBOUND saBound[1];

saBound[0].cElements = nElements;
saBound[0].lLbound = 0;

SAFEARRAY *pSA = SafeArrayCreate(VT_BSTR, 1, saBound);

if (pSA == NULL)
{
    return NULL;
}

for (int ix = 0; ix < nElements; ix++)
{
    BSTR pData = SysAllocString(elements[ix]);

    long rgIndicies[1];

    rgIndicies[0] = saBound[0].lLbound + ix;

    HRESULT hr = SafeArrayPutElement(pSA, rgIndicies, pData);

    _tprintf(TEXT("%d"), hr);
}
...