__declspec(dllexport):: vector <std :: string>

mat*_*tpm 4 c# c++ pinvoke vector declspec

我一直在努力研究如何将一个字符串数组从c ++ dll返回到ac#应用程序,但我仍然坚持如何做到这一点或在一个非常基本的层面上找到一篇文章.

假设我有以下代码.如何修复粗体线:

extern "C" {
    __declspec(dllexport) int GetANumber();

//unsure on this line:
    **__declspec(dllexport) ::vector<std::string> ListDevices();**

}

extern::vector<std::string> GetStrings()
{
    vector<string> seqs;
    return seqs;
}

extern int GetANumber()
{
    return 27;
}
Run Code Online (Sandbox Code Playgroud)

谢谢

马特

Sim*_*ier 6

您可以使用COM自动化SAFEARRAY类型,即使没有完整的COM(没有对象,没有类,没有接口,没有TLB,没有注册表等),只是使用DLL导出,因为.NET本身支持P/Invoke,这样的事情:

C++:

extern "C" __declspec(dllexport) LPSAFEARRAY ListDevices();

LPSAFEARRAY ListDevices()
{
    std::vector<std::string> v;
    v.push_back("hello world 1");
    v.push_back("hello world 2");
    v.push_back("hello world 3");

    CComSafeArray<BSTR> a(v.size()); // cool ATL helper that requires atlsafe.h

    std::vector<std::string>::const_iterator it;
    int i = 0;
    for (it = v.begin(); it != v.end(); ++it, ++i)
    {
        // note: you could also use std::wstring instead and avoid A2W conversion
        a.SetAt(i, A2BSTR_EX((*it).c_str()), FALSE);
    }
    return a.Detach();
}
Run Code Online (Sandbox Code Playgroud)

C#:

static void Main(string[] args)
{ 
    foreach(string s in ListDevices())
    {
        Console.WriteLine(s);
    }
}


[DllImport("MyUnmanaged.dll")]
[return: MarshalAs(UnmanagedType.SafeArray)] 
private extern static string[] ListDevices();
Run Code Online (Sandbox Code Playgroud)