7

我在这里的第一个问题:)

我正在使用一个用 C++ 编写的应用程序(游戏的地图编辑器),它的前端 UI 是用 C# 编写的。因为我是 C# 的新手,所以我试图在 C++ 方面做尽可能多的事情。

我想从 C# 调用一个 C++ 函数,该函数将返回具有简单变量类型(int 和 string)的结构列表,以便我可以用它们填充 UI 中的 listBox。这可能吗?我应该如何在 C# 中编写 dll 导入函数?

我尝试在这里搜索答案,但我只找到了关于如何将列表从 C# 传递到 C++ 的帖子。

C++ 代码:

struct PropData
{
PropData( const std::string aName, const int aId )
{
    myName = aName;
    myID = aId;
}

std::string myName;
int myID;
};

extern "C" _declspec(dllexport) std::vector<PropData> _stdcall GetPropData()
{
std::vector<PropData> myProps;

myProps.push_back( PropData("Bush", 0) );
myProps.push_back( PropData("Tree", 1) );
myProps.push_back( PropData("Rock", 2) );
myProps.push_back( PropData("Shroom", 3) );

return myProps;
}

C# 导入函数:

    [DllImport("MapEditor.dll")]
    static extern ??? GetPropData();

编辑:

在 Ed S 的帖子之后,我将 c++ 代码更改为 struct PropData { PropData( const std::string aName, const int aId ) { myName = aName; 我的身份证=身份证;}

    std::string myName;
    int myID;
};

extern "C" _declspec(dllexport) PropData* _stdcall GetPropData()
{
    std::vector<PropData> myProps;

    myProps.push_back( PropData("Bush", 0) );
    myProps.push_back( PropData("Tree", 1) );
    myProps.push_back( PropData("Rock", 2) );
    myProps.push_back( PropData("Shroom", 3) );

    return &myProps[0];
}

和 C# 到 [DllImport("MapEditor.dll")] static extern PropData GetPropData();

    struct PropData
    {
        string myName;
        int myID;
    }

    private void GetPropDataFromEditor()
    {
        List<PropData> myProps = GetPropData();
    }

但当然这不会编译,因为 GetPropData() 不会返回任何转换为​​列表的内容。

非常感谢 Ed S. 让我走到这一步!

4

1 回答 1

9

您将无法将其编std::vector入 C# 领域。你应该做的是返回一个数组。在面对互操作情况时,坚持基本类型会使事情变得简单得多。

std::vector保证 &v[0] 指向第一个元素并且所有元素都是连续存储的,所以只需将数组传回即可。如果您坚持使用 C++ 接口(我认为您不是),您将不得不研究一些更复杂的机制,例如 COM。

于 2012-01-18T17:46:35.783 回答