将字符串数组从Borland C ++传递到C#

时间:2019-05-02 15:55:58

标签: com borland-c++

我想将电子邮件地址字符串列表从Borland C ++传递到我的C#库。在我的C#辅助代码下方。我可以调用PrintName()方法,它可以工作。现在,我想打印电子邮件地址,但是如果我调用PrintEmails()函数,则不会发生任何事情。您能否建议我如何将多个电子邮件地址传递给C#库。

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

我已将上述C#库的TLB文件导入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 :(得分:0)

在我的情况下,下面的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);
}