分享

C#调用C++dll中的类

 gljin_cn 2016-07-18
               感谢xinen8721同学,项目需要今天参考了本文测试通过的代码。

C++定义:
////////////////////////////////////////////////////////
//自定义类别的头文件 WebICAdapter.h
#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);
}          

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多