1. 创建C#类库项目
2. 设置项目属性
3. 添加接口以及类源代码
using System;
using System.Runtime.InteropServices;
namespace AddCom
{
[Guid("8F5710FD-528A-4474-A673-47717F93EA88")]
public interface AddComInterface
{
[DispId(1)]
int Add(int a, int b);
}
[Guid("FFA2EB4B-1BBE-4332-8D3E-5E9F619A3FC9")]
[ClassInterface(ClassInterfaceType.None)]
public class AddComClass : AddComInterface
{
public int Add(int a, int b)
{
return a + b;
}
}
}
4. C++调用示例代码
#include
#include
#import "../../AddCom/AddCom/bin/Debug/AddCom.tlb"
using namespace AddCom;
int main()
{
CoInitialize(0);
AddCom::AddComInterfacePtr pAddCom(__uuidof(AddComClass));
int a = pAddCom->Add(1, 2);
std::cout << a << std::endl;
CoUninitialize();
return 0;
}
5. 结果
示例代码