olidev
olidev

Reputation: 20644

how to set an object into C++ from C#

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

E.g: 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 persons:

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 that '

persons

' list in a C++ source.

A sample is much appreciated!

Thanks in advance.

Upvotes: 0

Views: 547

Answers (1)

Michael Edenfield
Michael Edenfield

Reputation: 28338

You cannot pass a List<> to unmanaged C++, since it has no access to the CLR and wouldn't 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 that to an exported C++ function that expects an array. Depending on how much control you have over the C# and C++ definitions, there are some things you can do to make life easier on yourself:

First, define your C# type with interop in mind:

// 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;

Second, since C/C++ arrays aren't managed you'll need some other way to define how big it is; the easiest option is pass a second parameter to your C++ function that 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 simply call this method in C#; if you already have your populated List<Person> you would do this:

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

Upvotes: 1

Related Questions