[英]How to pass a list of objects from C++ to C#?
我的第一個問題:)
我正在使用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;
}
C#導入功能:
[DllImport("MapEditor.dll")]
static extern ??? GetPropData();
編輯:
在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];
}
和C#到[DllImport(“MapEditor.dll”)]靜態extern 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 ++接口(我認為您不是這樣),您將不得不研究一些更復雜的機制,如COM。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.