Passing a <String ^> List from C ++ to C #

Not like in C ++, so please help here. I have a DLL.net and am writing a wrapper so that DLL.net can be used later in C ++ and vb6 projects.

My code is:

C # class I want to call:

public class App { public App(int programKey, List<string> filePaths) { //Do something } } 

my C ++ project:

 static int m_programKey; static vector<std::string> m_fileNames; void __stdcall TicketReportAPI::TrStart(int iProgramKey) { m_programKey = iProgramKey; }; void __stdcall TicketReportAPI::TrAddFile(const char* cFileName) { string filename(cFileName); m_fileNames.push_back(filename); } void __stdcall TicketReportAPI::TrOpenDialog() { if(m_fileNames.size()> 0) { List<String^> list = gcnew List<String^>(); for(int index = 0; index < m_fileNames.size(); index++) { std::string Model(m_fileNames[index]); String^ sharpString = gcnew String(Model.c_str()); list.Add(gcnew String(sharpString)); } App^ app = gcnew App(m_programKey, list); } else App^ app = gcnew App(m_programKey); } 

If I try to compile a C ++ project, I get the following error:

App (int, System :: Collections :: Generic :: List ^) ': Conversion from' System :: Collections :: Generic :: List 'to' System :: Collections :: Generic :: List ^ 'is not possible

Is it possible to pass a managed list from C ++ to .net C #? If not, what are you guys suggesting that I pass the string array to my C # assembly?

Every help is appreciated, thanks in advance.

+4
source share
1 answer

You are missing ^ .

 List<String^>^ list = gcnew List<String^>(); ^-- right here 

You also need to switch list.Add to list->Add .

You use gcnew as you create something in a managed heap, and the resulting type is a managed descriptor ^ . This is roughly equivalent to using new to create an object in an unmanaged heap, and the resulting type is a pointer, * .

Declaring a local variable of type List<String^> (without ^ ) is a valid C ++ / CLI: this makes the local variable use stack semantics. There is no C # equivalent to this type of variable, so most of the .Net library does not work completely with it: for example, there are no copy constructors to work with assignment to variables without ^ . All managed APIs are waiting for parameters with types ^ , so in most cases you will want to use this for your local variables.

Important note: everything in this answer refers to reference types in .Net (which are declared in C # as a class , or in C ++ / CLI as a ref class or ref struct ). It does not apply to value types (C # struct , C ++ / CLI value class or value struct ). Value types (e.g. int , float , DateTime , etc.) are always declared and passed without ^ .

+12
source

Source: https://habr.com/ru/post/1485625/


All Articles