簡體   English   中英

如何使用清單 <pair<tstring,tstring> &gt;作為C#中C ++函數的參數

[英]How to use list<pair<tstring,tstring>> as parameter in C++ function from C#

我已經獲得了一個C ++庫,該庫的函數帶有list <pair <tstring,tstring >>的參數。 我需要為其他開發人員創建一個C#填充程序,以便能夠使用此庫。

我知道不允許封送通用類型,所以我想知道是否可以傳入模擬C ++中的配對列表的結構數組。

為了測試是否可行,我制作了一個簡單的C ++ DLL,該DLL模仿了我給出的DLL。 我在C ++測試DLL中創建了以下函數:

//In my C++ Test DLL
int MyFunction(list<pair<tstring, tstring>> &listParams)

在C#中,我創建了以下結構來模擬tstring對:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
struct myPair
{
    [MarshalAs(UnmanagedType.LPTStr)]
    public string Key;
    [MarshalAs(UnmanagedType.LPTStr)]
    public string Value;

    public myPair(string key, string val)
    {
        Key = key;
        Value = val;
    }
}

這也是我的C ++函數的PInvoke定義:

[System.Runtime.InteropServices.DllImport("MyTestLib.dll",  
CharSet = CharSet.Unicode, EntryPoint = "MyFunction")]
[return: MarshalAs(UnmanagedType.I4)]
public static extern Int32 MyFunction(
        [param:  MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]
        ref myPair[] listParams);

這是我的C#Test Shim中的代碼:

    public Int32 MyFunctionTest(Dictionary<string, string> testData)
    {
        Int32 retCode = 0;

        try
        {
            List<myPair> transfer = new List<myPair>();

            foreach (var entry in testData)
            {
                transfer.Add(new myPair(entry.Key, entry.Value));
            }

            myPair[] transferArray = transfer.ToArray();

            retCode = NativeMethods.MyFunction(ref transferArray);

        }
        catch (Exception ex)
        {
        }
        return retCode;
    }

盡管調用成功(不會崩潰),但是在我的C ++方法中,數據是亂碼且無效的。

有人知道這種映射是否可能嗎?

多虧了Wimmel,我才能找到答案。 這是為了創建一個“基於CLR的Shim”,它是C#和C ++庫之間的橋梁。

這是代碼:

//This is a method in a shim class which takes the C# objects
//and translates them to the C++ types required in the C++ dll 
Int32 myClass::Method(Dictionary<System::String^, System::String^> ^args)
{
    Int32 retCode = 0;
    list<pair<wstring, wstring>> listParams;

    for each (KeyValuePair<String^, String^>^ kvp in args)
    {
        listParams.insert(listParams.end(), 
            make_pair(msclr::interop::marshal_as<wstring>(kvp->Key),
            msclr::interop::marshal_as<wstring>(kvp->Value))
                          );
    }

    //My C++ Method
    MyFunction(listParams);

    return retCode;
}

我在C ++庫中對此進行了測試,並且傳入的數據正確無誤地通過了

暫無
暫無

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

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