之前项目中使用过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());
}
}
}