Click here to Skip to main content
15,888,733 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wish to know how to to pass the reference of an object of C# to C++ and Manipulate it in C++.

For example, I have a class in C#,

C#
class StudentScore
    
{
    
protected:
    
    int Maths;
    
    int Science;
    
    int Social;
    
    
    
public:
    
    int GetAverageScore()
    
    {
    
    return ((Maths+Science+Social)/3)
    
    }
    
    
    
    void SetMaths(int score)
    
    {
    
    Maths = score;
    
    }
    
    void SetScience(int score)
    
    {
    
    Science= score;
    
    }
    
    
    
    void SetSocial(int score)
    
    {
    
    Social= score;
    
    }
    
}


The object of StudentScore will be created in C# and values will be assigned as follows
C#
refObjStudentScore = new StudentScore(); 
SetMaths(85);
SetScience(80);
SetSocial(90);


Now I wish to pass the reference of object
C#
refObjStudentScore 
to a C++ DLL and invoke the function
C#
GetAverageScore 
to get average score in C++.

Could you please let me know how to achieve this.

Also, as a next step, I wish to pass collection of StudentScore to C++.

Any hint on this front will be of great help to me.
Posted

You cannot do it in any simple way. Typically, for interfacing between .NET assemblies and native DLLs, only primitive types, structures, as well as some select classes are used. Such classes, such as System.String, may have some predefined marshaling to a number of unmanaged types. The interfaced method itself should be a static method of some .NET class, which is equivalent to a "regular" (not object-oriented) C++ methods.

At the same time, you can use some managed classes, if they are the parameters of methods. For some, default marshaling is defined, for others, you can create custom marshaling. I would call it a pretty advanced topic. Please start here:
http://msdn.microsoft.com/en-us/library/d3cxf9f0%28v=vs.90%29.aspx[^].

—SA
 
Share this answer
 
What you want to do is use C++/CLI instead of plain C++. This will give you access to all of the managed types and libraries in the CLI. To make it easy, anything that is to be common between C# and C++ should be written on the C# side and #import'ed by C++ (this can be done by defining on the C++ side but is much more complicated to explain here).

Easiest route: make your executable managed (C# if possible) and each of the DLLs can be C# or C++/CLI (or VB.NET, yecch!).
 
Share this answer
 
Comments
nv3 14-Jul-13 3:58am    
My 5, and my congrats for reaching platinum level.
H.Brydon 14-Jul-13 14:31pm    
Thanks, and also thanks very much for your contribution. I suppose we have supported each other along the journey.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900