How to pass a list of objects from C ++ to C #?

My first question is here :)

I am working with an application written in C ++ (map editor for the game), which has a user interface in C #. Since I'm new to C #, I try to do as much as possible on the C ++ side.

From C # I want to call a C ++ function that will return a list of structures with simple types of variables (int and string) so that I can populate the listBox that I have in the user interface. Is it possible? How to write dll import function in C #?

I tried to find the answer here, but I only found a message on how to pass lists from C # to C ++.

C ++ Code:

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 # import function:

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

EDIT:

After a message from Ed S., I changed the C ++ code to 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]; } 

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

  struct PropData { string myName; int myID; } private void GetPropDataFromEditor() { List<PropData> myProps = GetPropData(); } 

but of course this does not compile, because GetPropData () does not return anything that is translated into a list.

Thanks a lot to Ed S. for having come this far!

+7
source share
1 answer

You cannot redirect std::vector to C # territory. Instead, you should return an array. Binding to basic types makes things much simpler when faced with interaction situations.

std::vector ensures that & v [0] points to the first element and that all elements are stored contiguously, so just pass the array back. If you are stuck with the C ++ interface as it is (which I don’t think), you will have to learn a more complex mechanism, such as COM.

+9
source

All Articles