1、 首先创建一个c#的类库项目。
2、 将AssemblyInfo.cs文件中的[assembly: ComVisible(false)]改为[assembly: ComVisible(true)],或者在项目属性中“应用程序”构选上“使程序集com可见”复选框。
3、 在项目属性中”生成”构选上”为com interop注册”复选框。
4、 参考以下代码及MSDN中COM 类示例(C# 编程指南):
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace Youtube
{
[Guid("FA1BEAD8-D5E2-4a70-ACDF-0A7FB4DA17FD")]
public interface IYoutubeService
{
void UploadFile();
}
[Guid("2BD4711C-CAC0-4df5-B167-447FCD00D55C"),
ClassInterface(ClassInterfaceType.AutoDispatch)]
public class YoutubeService : IYoutubeService
{
public void UploadFile()
{
Console.WriteLine("My Com Test!");
}
}
}
5、 编译,这时候会生成*.dll文件和*.tlb文件
6、 创建一个vc++的控制台项目,将*.tlb文件拷贝到vc++工程目录下
7、 Vc++代码如下:
#include "stdafx.h"
#import "Youtube.tlb"
#include
#include
#pragma comment(lib,"comsuppw.lib")
using namespace Youtube;
int _tmain(int argc, _TCHAR* argv[])
{
CoInitialize(NULL);
try
{
IYoutubeServicePtr service( __uuidof( YoutubeService ) );
service->UploadFile();
}
catch (const _com_error& e)
{
}
CoUninitialize();
return 0;
}
8、编译程序,并把之前的*.dll文件拷贝到和生成exe一起,运行程序则测试ok!
2、 将AssemblyInfo.cs文件中的[assembly: ComVisible(false)]改为[assembly: ComVisible(true)],或者在项目属性中“应用程序”构选上“使程序集com可见”复选框。
3、 在项目属性中”生成”构选上”为com interop注册”复选框。
4、 参考以下代码及MSDN中COM 类示例(C# 编程指南):
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace Youtube
{
[Guid("FA1BEAD8-D5E2-4a70-ACDF-0A7FB4DA17FD")]
public interface IYoutubeService
{
void UploadFile();
}
[Guid("2BD4711C-CAC0-4df5-B167-447FCD00D55C"),
ClassInterface(ClassInterfaceType.AutoDispatch)]
public class YoutubeService : IYoutubeService
{
public void UploadFile()
{
Console.WriteLine("My Com Test!");
}
}
}
5、 编译,这时候会生成*.dll文件和*.tlb文件
6、 创建一个vc++的控制台项目,将*.tlb文件拷贝到vc++工程目录下
7、 Vc++代码如下:
#include "stdafx.h"
#import "Youtube.tlb"
#include
#include
#pragma comment(lib,"comsuppw.lib")
using namespace Youtube;
int _tmain(int argc, _TCHAR* argv[])
{
CoInitialize(NULL);
try
{
IYoutubeServicePtr service( __uuidof( YoutubeService ) );
service->UploadFile();
}
catch (const _com_error& e)
{
}
CoUninitialize();
return 0;
}
8、编译程序,并把之前的*.dll文件拷贝到和生成exe一起,运行程序则测试ok!