C++、C# 互调用 之vc6 调用 C# com
1、vc6 调用 C# 编写的com
a、c#编写com
(1)VS2005中使用C#编写COM组件
建立C#编写的COM组件,项目类型为类库
配置:右键点击解决方案资源管理器中的AddCom,选择“属性”,选择“生成”,选择“为COM Interop注册(_P)”
打开AssemblyInfo.cs文件,设置[assembly: ComVisible(true)]
这用就可以生成AddCom.tlb文件
程序代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace AddCom
{
//可以通过//菜单的 “工具/guid生成”。
//注意要选择Define Guid{….}格式,并全//部保存下来,保存到哪都行,记事本呀什么的。
//因为在做VC程序/////////的时候要用到的。
[Guid("298D881C-E2A3-4638-B872-73EADE25511C")]
public interface AddComInterface
{
[DispId(1)]
int iadd(int a, int b);
[DispId(2)]
float ladd(float a, float b);
}
[Guid("2C5B7580-4038-4d90-BABD-8B83FCE5A467")]
[ClassInterface(ClassInterfaceType.None)]
public class AddComService : AddComInterface
{
public AddComService()
{
}
public int iadd(int a, int b)
{
int c = 0;
c = a + b;
return c;
}
public float ladd(float a, float b)
{
float c = 0;
c = a + b;
return c;
}
}
}b、VC6.0编写调用程序
使用VC6.0编写建立MFC应用程序UseCom,项目类型为MFC AppWizard(exe)
在stdafx.h添加:#import "AddCom.tlb" using namespace AddCom;
程序代码:void CUseComDlg::OnButtonUse() { // TODO: Add your control notification handler code here int dresult; float fresult; CString strResult; CoInitialize(NULL);//NULL换成0也可以 AddCom::AddComInterfacePtr p_Add(__uuidof(AddComService)); dresult = p_Add->iadd(1,2); fresult = p_Add->fadd(1.2,2.3); strResult.Format("int:%d \nfloat:%f",dresult,fresult); MessageBox(strResult,"计算结果",MB_OK); CoUninitialize(); }
浙公网安备 33010602011771号