在c#中使用托管c ++ dll

时间:2012-02-10 06:58:21

标签: c# c++

**unmanaged class**

这是非托管类声明

#ifdef EXPORT_CLASS
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
public class DLL_EXPORT cppclass
{
private:
string x;
public:
cppclass();
~cppclass();
string native();
};


**UNMANAGED CLASS DEFINITION**

这是非托管类定义

 cppclass::cppclass()
{
x="hello";
};
cppclass::~cppclass()
{
};
string cppclass::native()
{
return x;
};

**MANAGED CLASS**

这是托管类声明

public __gc class Mclass
{
//private:
public:
cppclass * obj;
public:
Mclass();
~Mclass();
string native();

};

**MANAGED CLASS DEFINITION**

//这是托管类定义

#include"managed.h"
Mclass::Mclass()
{
    obj=new cppclass();
};
Mclass::~Mclass()
{
    delete obj;
};
string Mclass::native() 
{
return  obj->native();
};

Now all this is made into a dll and imported in a c# project


using managed;

 namespace ConsoleApplication1
 {
 class Program
 {
    static void Main(string[] args)
    {
        managed.Mclass first = new Mclass();
        String x=first.nativ();
        Console.Out.WriteLine(x);
    }

}

}

错误来自语言

不支持Managed.Mclass.nativ()

1 个答案:

答案 0 :(得分:2)

您正在从C ++ / CLI包装器类返回本机字符串。您需要返回托管的.net字符串。包装类必须转换参数并将本机类的值返回到适当的托管类。