簡體   English   中英

如何通過COM互操作將字符串集合從C#返回到C ++

[英]How to return a collection of strings from C# to C++ via COM interop

我在C#中為一些Display方法創建了一個com組件,它返回一個String List

如下所示。 在v ++中,我使用std :: lst來捕獲Disp()的返回值但是它

給出編譯器錯誤,Disp不是類的成員。 我將返回類型設為void

它工作正常。 什么我可以修改,以便Disp返回一個List和main(c ++)我必須使用

這個回報值。

Public interface ITest
{
    List<string> Disp();
}

class TestLib:ITest
{
    List<string> Disp()
    {
        List<string> li=new List<string>();
        li.Add("stack");
        li.Add("over");
        li.Add("Flow");

        return li;
    }
}

編譯並創建了Test.dll成功,還有test.tlb。 現在在用c ++編寫的main函數中

#include<list>
#import "..\test.tlb"
using namespace Test;
void main()
{
    HRESULT hr=CoInitialize(null);

    ITestPtr Ip(__uuidof(TestLib));

    std::list<string> li=new std::list<string>();

    li=Ip->Disp();
}

當我嘗試編譯它時,我的代碼出了什么問題

'Disp':不是TestLib的成員:ITest

如何解決這個PLZ幫助我....當我讓它返回類型作為void在類中它工作正常。我做的錯誤????

即使您修正了拼寫錯誤,這也無法正常工作。 COM interop沒有從List<T>到COM中的某些內容的標准映射,它肯定不會將它映射到std::list 不允許泛型出現在COM接口中。

UPDATE

我嘗試使用ArrayList作為返回類型,因為這是非泛型的我認為也許tlb會包含它的類型信息。 IList所以我嘗試了IList 這也沒有用( #import語句產生了一個引用IList但沒有為它定義的.tlh文件。)

因此,作為一種解決方法,我嘗試聲明一個簡單的列表界面。 代碼最終如下:

[Guid("7366fe1c-d84f-4241-b27d-8b1b6072af92")]
public interface IStringCollection
{
    int Count { get; }
    string Get(int index);
}

[Guid("8e8df55f-a90c-4a07-bee5-575104105e1d")]
public interface IMyThing
{
    IStringCollection GetListOfStrings();
}

public class StringCollection : List<string>, IStringCollection
{
    public string Get(int index)
    {
        return this[index];
    }
}

public class Class1 : IMyThing
{
    public IStringCollection GetListOfStrings()
    {
        return new StringCollection { "Hello", "World" };
    }
}

所以我有自己的(非常簡單的)字符串集合接口。 請注意,我的StringCollection類不必定義Count屬性,因為它從List<string>繼承了完美的優點。

然后我在C ++方面有這個:

#include "stdafx.h"
#import "..\ClassLibrary5.tlb"

#include <vector>
#include <string>

using namespace ClassLibrary5;

int _tmain(int argc, _TCHAR* argv[])
{
    CoInitialize(0);

    IMyThingPtr thing(__uuidof(Class1));

    std::vector<std::string> vectorOfStrings;

    IStringCollectionPtr strings(thing->GetListOfStrings());
    for (int n = 0; n < strings->GetCount(); n++)
    {
        const char *pStr = strings->Get(n);
        vectorOfStrings.push_back(pStr);
    }

    return 0;
}

我必須手動復制字符串集合的內容一個適當的C ++標准容器,但它的工作原理。

可能有一種方法可以從標准集合類中獲取正確的類型信息,因此您不必創建自己的集合接口,但如果沒有,這應該可以正常使用。

或者,你看過C ++ / CLI嗎? 雖然它仍然不會自動將CLR集合轉換為std容器,但它可以非常無縫地工作。

看起來有幾個拼寫錯誤。 在C#中,您聲明了一個名為TestLib的類,但正在嘗試構建一個TestCls。 另外,類和方法都不是公共的(至少在Disp上應該是編譯錯誤,因為接口必須公開實現)。

猜猜:Disp()未公開

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM