我的第一个问题:)
我正在使用一个用 C++ 编写的应用程序(游戏的 map 编辑器),它具有用 C# 编写的前端 UI。因为我是 C# 的新手,所以我尝试在 C++ 方面做尽可能多的事情。
我想从 C# 调用一个 C++ 函数,该函数将返回具有简单变量类型(int 和字符串)的结构列表,以便我可以用它们填充 UI 中的列表框。这可能吗?我应该如何在 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++ 代码更改为 结构 PropData { PropData( const std::string aName, const int aId ) { 我的名字=一个名字; 我的 ID = aId;
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")] 静态外部 PropData GetPropData();
struct PropData
{
string myName;
int myID;
}
private void GetPropDataFromEditor()
{
List<PropData> myProps = GetPropData();
}
但是当然这不会编译,因为 GetPropData() 不会返回任何转换为列表的内容。
非常感谢 Ed S. 让我走到这一步!
最佳答案
您将无法将 std::vector
编码到 C# 领域。你应该做的是返回一个数组。在面对互操作情况时,坚持使用基本类型会使事情变得更加简单。
std::vector
保证 &v[0] 指向第一个元素并且所有元素都是连续存储的,因此只需将数组传回即可。如果您坚持使用 C++ 接口(interface)(我认为您不是),您将不得不研究一些更复杂的机制,例如 COM。
关于c# - 如何将对象列表从 C++ 传递到 C#?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8914756/