Passing objects between C# library and C++ (CLR)

2019-09-05 21:43发布

问题:

How to pass objects from C# library to C++.

I can call a function which returns void or int without any issue.

Now consider the following function in C#,

List<CSharpClass> CSharpFunction(string Input)

where my C# class contains,

public class CSharpClass
{ 
    string mystring = string.Empty;
    byte[] bytearray = null;        

    public byte[] bytearray 
    {
        get { return bytearray ; }
        set { bytearray = value; }
    }

    public string mystring 
    {
        get { return mystring ; }
        set { mystring = value; }
    }      
}

Now, I want use this List in my C++. So I have created,

  typedef std::vector<class CSharpClass>  MyDetailList;

Is it the right way ?? If not what I need to use in C++?

回答1:

If you want to call a C# dll from C++ code, you can follow this article. In a nutshell, you're going to have to:
- Write a Managed DLL containing your CSharpClass
- Register the Managed DLL for Use with COM or with Native C++
- Call the Managed DLL from Native C++ Code

This SO question is also relevant, and contains alternative solutions if you want to avoid using COM


Initial misguided answer:

You can check this article for a fairly good tutorial. In a nutshell, you're going to have to:
- Compile a dll from your c++ code
- marshall ("translate") your class between C# and C++
- load the dll from C#, by using DllImport declaration
- call the imported method