How to set an object in C ++ from C #

I want to configure a C ++ project with C #.

For example: if I have this class in C #:

public class Person { public Person(){} public string FirstName {get; set;} public string LastName {get; set;} public int Age {get; set;} } 

Then I have a list of people:

 Person per1 = new Person(); per1.FirstName = "Per1"; per1.LastName = "Last"; per1.Age = 20; Person per2 = new Person(); per2.FirstName = "Per2"; per2.LastName = "Last2"; per2.Age = 21; 

then I have:

 List<Person> persons = new List(); persons.Add(per1); persons.Add(per2); 

My question is: how can I pass this'

human

'in C ++ source.

Sample is greatly appreciated!

Thanks in advance.

0
source share
1 answer

You cannot pass List<> unmanaged C ++, since it does not have access to the CLR and does not know what to do with it.

What you can do is define a structure in C ++ that matches the layout of your C # class and pass it to the exported C ++ function that expects the array. Depending on how much control you have over the definitions of C # and C ++, you can do some things to make life easier:

First, define your C # type based on the interaction:

 // In C#: [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct Person { [MarshalAs(UnmanagedType.LPWStr)] public string FirstName; [MarshalAs(UnmanagedType.LPWStr)] public string LastName; public int Age; } // In C++ typedef struct tagPerson { LPWSTR firstname; LPWSTR lastname; LONG age; } Person; 

Secondly, since C / C ++ arrays are not managed, you will need another way to determine how large it is; the easiest option is to pass the second parameter to your C ++ function, which is the length.

 // In C++ extern "C" __declspec( dllexport ) void MyFunction(LONG count, Person[] people); // In C# [DllImport("mydll.dll")] public static extern void MyFunction( int count, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] Person[] people); 

Then you can just call this method in C #; if you already have your own populated List<Person> , you would do this:

 var personsArray = persons.ToArray(); NativeMethods.MyFunction(personsArray.Length, personsArray); 
+1
source

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


All Articles