最近因为一个C++项目需要用到以前一个C#项目中的代码,C#的DLLC++调用也有一些类型转换的问题,就直接尝试用C#编写COM组件供C++调用,
查了些资料整理了一下并在此记录
这种使用情况应该不多,终究是一种方法,希望对读者能有所帮助
工具:VS2010
环境:win764 32
步骤一:C#编写COM组件
选择类库,属性,应用程序
生成
签名
勾选为程序集签名,新建密钥文件,去掉密码保护
以上为工程属性设置。
以下为代码部分:
首先确保AssemblyInfo.cs里面的
[assembly: ComVisible(true)]为true值
以下为主要CS文件内容:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace COM_CS
{
[ComVisible(true)]
[Guid("52AD7263-9EF1-48d5-8019-E01B84E9C4DA")]
public interface IMyClass //必须有一个interface的虚类接口
{
void Initialize();
void Dispose();
int Add(int x, int y);
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[Guid("FB0DC677-EF3C-40ad-94A3-1AAA0DC0AA3E")]
[ProgId("DemoCom.ComTest")]
public class ComTest : IMyClass//在此继承接口并实现
{
public void Initialize()
{ //TODO:handle code
}
public void Dispose()
{ //TODO:handle code
}
public int Add(int x, int y)
{
return x + y;
}
}
}
至此,COM组件编写完毕,然后要注册
步骤二:注册COM组件
注册命令为regasm,不同于C++的注册regsvr32
需要增加环境变量或者进入命令提示符CMD在目录C:\Windows\Microsoft.NET\Framework\v4.0.30319或者C:\Windows\Microsoft.NET\Framework64\v4.0.30319(根据系统)下使用regasm然后拖动生成的DLL文件进行注册
*需要注意的是,注册成功后,使用的时候需要把DLL放在供调用程序的根目录下方可调用
步骤三:C++调用部分代码
#include <iostream>
#include <ObjBase.h>
//#import "G:\sjx\测试工程\COM组件测试\ComTest\COM_CS\bin\Debug\COM_CS.tlb" named_guids raw_interfaces_only
#import "D:\test\COM_CS.tlb" named_guids raw_interfaces_only//与DLL相匹配的TLB文件路径
using namespace std;
int main()
{
long a=1;
long b=2;
long c=0;
char mes[64];
CoInitialize(NULL);//初始化COM环境
COM_CS:: IMyClassPtr pDotNetCOMPtr;//虚类接口的智能指针
HRESULT hRes =pDotNetCOMPtr.CreateInstance(__uuidof(COM_CS::ComTest));//判断智能指针是否正确获取
if(hRes==S_OK)
{
cout<<"输入a"<<endl;
cin>>a;
cout<<"输入b"<<endl;
cin>>b;
pDotNetCOMPtr->Add(a,b,&c);
pDotNetCOMPtr.Release();
CoUninitialize();//释放资源
sprintf(mes,"C=%d",c);
cout<<mes<<endl;
//MessageBox(NULL,mes,"TEST",MB_OK);
getchar();
getchar();
return c;
}
sprintf(mes,"COM加载失败);
cout<<mes<<endl;
//MessageBox(NULL,mes,"TEST",MB_OK);
getchar();
getchar();
return 1;
}