【问题标题】:Passing string array from Borland C++ to C#将字符串数组从 Borland C++ 传递到 C#
【发布时间】:2019-05-02 15:55:57
【问题描述】:

我想将电子邮件地址字符串列表从 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);
    }
} 

我已将上述 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;

【问题讨论】:

  • SafeArrayCreate() 调用与 C# 代码不匹配。 VT_VARIANT 的安全数组将是 C# 端的 object[]。请改用 VT_BSTR。
  • 谢谢汉斯。有效。请参阅答案部分中我的 C++ 方面。

标签: com borland-c++


【解决方案1】:

以下 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);
}

【讨论】:

  • 看来您应该接受您的回答 - 我赞成您记录解决方案。
猜你喜欢
  • 2015-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多