詳細見:Interoping .NET and C++ through COM - CodeProject,
個人理解:
1、C#生成的dll相當於com server
2、C++呼叫相當於com client
3、client 要訪問 server 的動態庫,需要進行assembly註冊,見:Registering Assemblies with COM - .NET Framework | Microsoft Learn。
4、註冊:管理員許可權C:\Windows\Microsoft.NET\Framework64\v4.0.30319>regasm D:\wjw\gitee\SoftwareLicense-master\Register\bin\Debug\Register.dll
5、註冊tlb:C:\Windows\Microsoft.NET\Framework64\v4.0.30319>regasm D:\wjw\gitee\SoftwareLicense-master\Register\bin\Debug\Register.dll /tlb:Register.tlb
6、dll的位置:
-
The global assembly cache (must be a strong-named assembly).C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools>gacutil /i D:\wjw\gitee\SoftwareLicense-master\Register\bin\Debug\Register.dll
-
In the application directory. Assemblies loaded from the application path are only accessible from that application.
-
Along an file path specified with the /codebase option to Regasm.exe.
7、將生成的tlb複製到c++專案當前資料夾
8、匯入c++:
#include<atlcomcli.h>
#import "Register.tlb"
9、呼叫:
CoInitialize(NULL);
myInterfacePtr dll(__uuidof(ComDll));
BSTR str = SysAllocString(L"");
bool b = dll->check("", &str);
char* p = _com_util::ConvertBSTRToString(str);
qInfo() << p;
SysFreeString(str);
以上程式碼,ComDll為com server 類,check函式在c#為out string.