创建C#DLL

1. 创建classlibrary

2.编写一个COM接口和一个COM类

  [Guid("DBE0E8C4-1C61-41f3-B6A4-4E2F353D3D05")]        

public interface IManagedInterface       

  {             int PrintHi(string name);         }

  

      [Guid("C6659361-1625-4746-931C-36014B146679")]        

public class InterfaceImplementation : IManagedInterface    

     {             public int PrintHi(string name)             {                 Console.WriteLine("Hello, {0}!", name);                 return 33;             }         }

3.在PROJECT上点击右键,选择属性---》bulid,选择registry from com interep.

4.一定要以管理员的方式运行 VS

5.在BIN里面有dll。可以不用 CSC 那种命令行了,happy.

6.怎么在C#中引用 :

添加引用

using System.Runtime.InteropServices;

using ClassLibrary2;

 [DllImport("ClassLibrary2.dll", SetLastError = true)]        

 public static extern int DoWork(bool flags);      

ClassLibrary2.Class1 c1 = new Class1();            

B1.Content =c1.DoWork(true);        

 7. 如果是要发布给c++,那就对不起了,还有好多步骤。

7.1请添加以下属性

 [InterfaceType(ComInterfaceType.InterfaceIsDual)]
    [Guid("6EEF31AA-4D8B-4BE6-9254-F9C971E80BAB")]
    public interface IF1

 {
        [DispId(1)]
        int DoWork(bool user);
      
    }

 [ProgId("ClassLibrary2.DotNet")]
   [ClassInterface(ClassInterfaceType.None)]
   [Guid("51B24524-2B52-4EDB-89FF-B9F2A3BB8B44")]

7.2

请在debug中运行sn -k TestKeyPair.snk

AssemblyInfo.cs中

[assembly: ComVisible(true)]

 [assembly: AssemblyKeyFile("TestKeyPair.snk")]

7.3

gacutil /i MyInterop.dll

REGASM MyInterop.dll /tlb:com.MyInterop.tlb 

Register your assembly for COM by using the REGASM command along with the "/tlb" option to generate a COM type library.

8在c++项目中 

#import "<>\\com.ClassLibrary2.tlb" named_guids raw_interfaces_only

build

得到\com.ClassLibrary2.tlh

9在c++项目中

#pragma comment(lib,"<>\com.ClassLibrary2.tlh")

10 请找到uuid号码,用CoCreateInstance得到实例

CoInitialize(NULL);   //Initialize all COM Components    

HRESULT hr = CoInitialize(NULL);

 CLSID clsid = __uuidof(ClassLibrary2::ClassLibrary2);  

 IID iid = __uuidof(ClassLibrary2::IF1);

11:

 ClassLibrary2::IF1 *ptr;  

hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER,__uuidof(ClassLibrary2::IF1), (LPVOID*)&ptr);  

long * rs;  

rs = (long *)malloc(sizeof(long)* 1);  

ptr->DoWork(true, rs);  

CoUninitialize();

或者12:

   IClassFactory * p_classfactory;

 hr = CoGetClassObject(clsid, CLSCTX_INPROC_SERVER, NULL, IID_IClassFactory,(LPVOID*)&p_classfactory);

 ClassLibrary2::IF1 *ptr2;  p_classfactory->CreateInstance(NULL, __uuidof(ClassLibrary2::IF1), (LPVOID*)&ptr2);

  ptr2->DoWork(true, rs);

其实还有13:

CComPtr

但是这个是VC++专属类

#include <atlbase.h>  

CComPtr<ClassLibrary2::IF1> ptr3;

 ptr3.CoCreateInstance(clsid);

http://www.codeproject.com/Articles/12673/Calling-Managed-NET-C-COM-Objects-from-Unmanaged-C

http://www.myexception.cn/vc-mfc/145728.html

原文地址:https://www.cnblogs.com/gaoxianzhi/p/3799735.html