DLL库类的导出,C#的调用

在DLL库的编写中,如果想要把DLL库中写的类导出,并且在C#中进行使用,我们需要先初始化获取类的指针,然后我们可以通过指针对类进行调用,使我们能正常的使用类中的功能。

 

#ifdef DLL_API
#else
#define DLL_API extern "C"__declspec(dllexport)
#endif
 
class WebICAdapter
{
public:
WebICAdapter(void);
~WebICAdapter(void);
// 测试add函数
int add(int p1, int p2);
};
 
// 返回类别的实例指针
DLL_API void* classInit(void **clsp);
DLL_API int add(WebICAdapter* p, int p1,int p2);
 

//自定义类别的头文件WebICAdapter.cpp
//=========导出函数============
// 返回类别的实例指针
void* classInit(void **clsp)
{
WebICAdapter* p = new WebICAdapter();
*clsp = p;
return clsp;
}
int add(WebICAdapter* p, int p1, int p2)
{
return p->add(p1,p2);
}
//==========类别实现===========
WebICAdapter::WebICAdapter(void)
{
}
WebICAdapter::~WebICAdapter(void)
{
}
// 测试add函数
int WebICAdapter::add(int p1, int p2)
{
return p1+p2;
}
 
C#定义和调用:

using System.Runtime.InteropServices;
......
       //--------------DLL接口定义-----------
       [DllImport("SWWebICAdapter.dll", EntryPoint ="classInit", CharSet = CharSet.Auto, CallingConvention =CallingConvention.StdCall)]
       public static extern int classInit(ref int clsPoint);
 
       [DllImport("SWWebICAdapter.dll", EntryPoint = "add",CharSet = CharSet.Auto,
 
CallingConvention =CallingConvention.StdCall)]
       public static extern int add(ref int clsPoint, int p1, int p2);
       // DLL中的类实例指针
       private int _clsPoint = 0;
 
       // -----------------------------------
       public SWWebIC()
       {
           InitializeComponent();
           // 初始化DLL类实例
           _clsPoint = classInit(ref _clsPoint);
       }
......
       private void buttonDevice_Click(object sender, EventArgs e)
       {
           int n = add(ref _clsPoint, 11, 12);
           MessageBox.Show("计算结果:" + n);
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值