C#-调用C++写的dll

之前项目中使用过C#调用C++生成的dll,这里暂时记录以下;
C++的dll在同一个exe下多线程使用,需要特别注意,可以在dll内new 对象,然后把对象指针以long形式给C#使用,每次使用带有long参数,可以找到对应的对象;在使用完毕后,销毁long所指向的对象;
注意:C++的dll申请的内存,由C++提供接口,C#调用来释放;
DLLTEST:
h头文件:

#include<iostream>
using namespace std;

class CAdd
{
public :
	int Add(const int a, const int b)
	{
		return a+b;
	}
};

extern "C" _declspec(dllexport) void* DllCreateObject();
extern "C" _declspec(dllexport) int DllAdd(void* pCAdd, int a, int b);
extern "C" _declspec(dllexport) void DllDestory(void* pCAdd);

cpp文件:

#include"cDll.h"
void* DllCreateObject()
{
	CAdd* p = new CAdd();
	return p;
}

int DllAdd(void* pCAdd, int a, int b)
{
	CAdd* p = (CAdd*)pCAdd;
	return p->Add(a, b);
}

void DllDestory(void* pCAdd)
{
	delete pCAdd;
}

TESTUSE:

封装c++中的DLL类:

test类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace TestUse
{
    class DllInterface
    {
        //创建DLL类实例接口
        [DllImport("DllTest.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr DllCreateObject();

        //两数相加
        [DllImport("DllTest.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int DllAdd(IntPtr dllObject, int a, int b);

        //摧毁DLL类实例接口
        [DllImport("DllTest.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void DllDestory(IntPtr dllObject);
    }

    class Test
    {
        public int TestAdd(int a, int b)
        {
            IntPtr dllObject = DllInterface.DllCreateObject();
            int c = DllInterface.DllAdd(dllObject, a, b);
            DllInterface.DllDestory(dllObject);
            return c;
        }
    }
}

C#程序调用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestUse
{
    class Program
    {
        static void Main(string[] args)
        {
            Test testObject = new Test();
            int val = testObject.TestAdd(3, 4);
            Console.WriteLine(val.ToString());
        }
    }
}
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黑山老妖的笔记本

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值