Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call C++ class from C#

Tags:

c++

c#

c++-cli

I suppose I have to create a managed C++ code to wrap the native C++. But I have the problem while trying to wrap an array used in function parameter whose type is defined in native C++. The native C++ code is as follows:

//unmanageCPP.h
class __declspec(dllexport) unmanageMoney
{
public:
    unmanageMoney(int a, int b) { rmb = a; dollar = b; }
    unmanageMoney() { rmb = 0; dollar = 0; }
    int rmb;
    int dollar;
};

class __declspec(dllexport) unmanageSum
{
public:
    //how to wrap this funciton?
    int addDollar(unmanageMoney a[], unmanageMoney b[]);
};

//unmanageCPP.cpp
#include "unmanaged.h"

int unmanageSum::adddollar(unmanageMoney a[], unmanageMoney b[])
{
    return a[0].dollar + b[0].dollar;
}

Could anyone tell me how to write the manageCPP.h? Thanks very much!

Update

I compose the manageCPP.h as follows, but I don't know how to write addDollar()

//first, I wrap the class unmanageMoney for use in manageSum::addDollar()
public ref class manageMoney
{
private:
    unmanageMoney* mMoney;
public:
    unmanageMoney getMoney()
    {
        return *mMoney;
    }
    manageMoney(int a, int b)   { mMoney = new unmanageMoney(a, b); }
    ~manageMoney()  { delete mMoney; }
};

public ref class manageSum
{
    // TODO: Add your methods for this class here.
private:
    unmanageSum *mSum;
public:
    manageSum()
    {
        mSum = new unmanageSum();
    }
    ~manageSum()
    {
        delete mSum;
    }

    //it must be wrong if I code like this, for unmanageSun::adddollar() only
    // receives unmanageMoney as arguments. So what should I do?
    int adddollar(manageMoney a[], manageMoney b[])
    {
            return mSum->adddollar(a, b);
    }

};
like image 749
ChanDon Avatar asked Nov 14 '22 03:11

ChanDon


1 Answers

You create a C++/CLI source file with

public ref class SomethingOrOther
{
    //...
};

and set the compile options to use the /clr option.

Beyond that, it's almost the same as writing native C++. You'll #include the header file for the class you want to reuse, create instances and call their member functions, just the same as normal C++. But anything inside that ref class will be visible to C#.

And you do NOT put __declspec(dllexport) on the class. Not ever. It's useful for functions, but creates misery when used with classes.

like image 64
Ben Voigt Avatar answered Dec 15 '22 06:12

Ben Voigt