C++调用 c#生成的dll

详细见: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);

以上代码,myInterface为ComDll对应的接口,ComDll为com server 类,check函数str在c#为out string.

10、regasm替代:

reg import pathtoreg\Register.reg 实现静默导入

reg为regasm /regFile选项生成的注册表项,用于客户端注册表的导入

posted @ 2024-06-28 17:50  jwwry  阅读(13)  评论(0编辑  收藏  举报