C++类托管封装,C#调用C++类

简化版Demo地址:https://download.csdn.net/download/qq_26739115/85178614

第一:在C++环境中启动C#语言的公共语言运行支持,如下所示

 

第二:根据VS当前的.NET环境引用托管中间件mscorlib库,默认此库在此目录的各个版本文件下:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework

 

 

 

 

 

 第三:编写托管类,将C++类进行托管

1、C++类头文件和实现

//头文件
class  DsGePoint3d{
public:
	DsGePoint3d();
	DsGePoint3d(double x,double y,double z);
	double distanceTo(const DsGePoint3d& pnt)const;
	ArxGePoint3d ConvertArxGePoint3d()const;
	ArxGePoint2d ConvertArxGePoint2d()const;

public:
	double x;
	double y;
	double z;
};

  

 1 DsGePoint3d::DsGePoint3d():x(0.0),y(0.0),z(0.0)
 2 {
 3 
 4 }
 5 
 6 DsGePoint3d::DsGePoint3d(double x,double y,double z):x(x),y(y),z(z)
 7 {
 8 
 9 }
10 
11 double DsGePoint3d::distanceTo(const DsGePoint3d& pnt) const
12 {
13     ArxGePoint3d tp(x,y,z);
14     return tp.distanceTo(pnt.ConvertArxGePoint3d());
15 }
16 
17 ArxGePoint3d DsGePoint3d::ConvertArxGePoint3d() const
18 {
19     ArxGePoint3d gepnt(x,y,z);
20     return gepnt;
21 }
22 
23 ArxGePoint2d DsGePoint3d::ConvertArxGePoint2d() const
24 {
25     ArxGePoint2d gepnt(x,y);
26     return gepnt;
27 }

2、托管封装头文件和实现

文件说明:

 

 

 

 

 1 #pragma once
 2 /************************************************************************/
 3 /* 将C++非托管类进行托管                                                */
 4 /************************************************************************/
 5 #define LX_DLL_CLASS_EXPORTS
 6 #include "DsEntity.h"
 7 #include <msclr\marshal_cppstd.h> 
 8 using namespace msclr::interop;
 9 using namespace System;
10 
11 namespace MgDsEntity
12 {
13     public ref class MgDsGePoint3d
14     {
15     public:
16         MgDsGePoint3d();
17         MgDsGePoint3d(double x,double y,double z);
18         ~MgDsGePoint3d();
19 
20         double distanceTo(MgDsGePoint3d^ pnt);
21     public:
22         double X();
23         double Y();
24         double Z();
25     private:
26         DsGePoint3d* m_Impl;
27     };
28 }
 1 #include "MgDsEntity.h"
 2 
 3 namespace MgDsEntity
 4 {
 5 
 6 
 7     MgDsGePoint3d::MgDsGePoint3d()
 8     {
 9         m_Impl = new DsGePoint3d();
10     }
11 
12     MgDsGePoint3d::MgDsGePoint3d(double x,double y,double z)
13     {
14         m_Impl = new DsGePoint3d(x,y,z);
15     }
16 
17     MgDsGePoint3d::~MgDsGePoint3d()
18     {
19         delete m_Impl;
20     }
21 
22     double MgDsGePoint3d::distanceTo(MgDsGePoint3d^ pnt)
23     {
24         DsGePoint3d Point(pnt->X(),pnt->Y(),pnt->Z());
25         return m_Impl->distanceTo(Point);
26     }
27 
28     double MgDsGePoint3d::X()
29     {
30         return m_Impl->x;
31     }
32 
33     double MgDsGePoint3d::Y()
34     {
35         return m_Impl->y;
36     }
37 
38     double MgDsGePoint3d::Z()
39     {
40         return m_Impl->z;
41     }
42 
43 }

 

3、使用方式和普通C#库使用方式一样,引入库文件,申明命名空间,使用对象

 

参考博客: https://blog.csdn.net/aoshilang2249/article/details/42317367

posted @ 2022-04-19 17:20  百年一梦  阅读(866)  评论(0编辑  收藏  举报