如何从C#调用C ++类

时间:2011-01-24 04:41:24

标签: c# c++ c++-cli

我想我必须创建一个托管C ++代码来包装本机C ++。但是我在尝试包装函数参数中使用的数组时遇到了问题,该数组的类型是在本机C ++中定义的。本机C ++代码如下:

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

有谁能告诉我如何编写manageCPP.h?非常感谢!

更新

我将manageCPP.h编写如下,但我不知道如何编写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);
    }

};

1 个答案:

答案 0 :(得分:1)

使用

创建C ++ / CLI源文件
public ref class SomethingOrOther
{
    //...
};

并设置编译选项以使用/clr选项。

除此之外,它与编写本机C ++几乎相同。您将#include要重用的类的头文件,创建实例并调用其成员函数,与普通C ++相同。但是ref class内的任何内容都将对C#可见。

你不要把__declspec(dllexport)放在课堂上。永远不会。它对函数很有用,但在与类一起使用时会产生痛苦。