Cou*_*ken 7 c# c++ dll cross-language dllimport
我的第一个问题:)
我正在使用C++(一个游戏的地图编辑器)编写的应用程序,它具有用C#编写的前端UI.因为我是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;
}
Run Code Online (Sandbox Code Playgroud)
C#导入功能:
[DllImport("MapEditor.dll")]
static extern ??? GetPropData();
Run Code Online (Sandbox Code Playgroud)
编辑:
在Ed S.的帖子之后,我将c ++代码更改为struct PropData {PropData(const std :: string aName,const int aId){myName = aName; myID = 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];
}
Run Code Online (Sandbox Code Playgroud)
和C#到[DllImport("MapEditor.dll")]静态extern PropData GetPropData();
struct PropData
{
string myName;
int myID;
}
private void GetPropDataFromEditor()
{
List<PropData> myProps = GetPropData();
}
Run Code Online (Sandbox Code Playgroud)
但当然这不会编译,因为GetPropData()不会返回任何转换为列表的内容.
非常感谢Ed S.让我走到这一步!
你无法将其编std::vector入C#领域.你应该做的是返回一个数组.在面对互操作情况时,坚持基本类型会使事情变得更加简单.
std::vector保证&v [0]指向第一个元素并且所有元素都是连续存储的,所以只需将数组传回.如果您坚持使用C++接口(我认为您不是这样),您将不得不研究一些更复杂的机制,如COM.