C++调用C#编写的COM
1、建C#类库CSharpCOMComponent,接口IMyClass,类MyClass,方法Find调用Win32API查找名为“计算器”的窗体。
程序代码:
using System;
using System.Runtime.InteropServices;
namespace CSharpCOMComponent
{
[ComVisible(true)]
[Guid("6BF1BC54-4006-4F0D-B6DC-B739F9A3236E")]
public interface IMyClass
{
[DispId(1)]
int Find();
}
[ComVisible(true)]
[Guid("32F230A4-3822-419A-A7A2-ED9054B02A74")]
[ClassInterface(ClassInterfaceType.None)]
public class MyClass : IMyClass
{
[DllImport("user32.dll", EntryPoint = "FindWindow")]
private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
public int Find()
{
return (int)FindWindow(null, "计算器");
}
}
}
2、为COM修改配置,生成密钥文件等,这些你应该懂了吧?
3、编译COM,将得到的文件放到相应目录下;
4、在C++里面调用,如下:
程序代码:
#include "stdafx.h"
#include <iostream>
#import "C:\CSharpCOMComponent.tlb" named_guids raw_interfaces_only
int _tmain(int argc, _TCHAR* argv[])
{
CoInitialize(NULL);
CSharpCOMComponent::IMyClassPtr classPtr;
classPtr.CreateInstance(CSharpCOMComponent::CLSID_MyClass);
long calcHwnd;
long * lPtr = &calcHwnd;
classPtr->Find(lPtr);
std::cout<<calcHwnd;
getchar();
}
得到结果:7607834,完全没有问题!