C# COM Component
The document below tells you every detail about how to make and register a C# .NET Managed Assembly for COM Interop:
How to call a managed DLL from native Visual C++ code in Visual Studio.NET or in Visual Studio 2005
The only defect is that it is targeted at Visual Studio 2005. Hence, in Visual Studio 2013, there are some minor differences.
- How to open Visual Studio 2013 Command Prompt
Select Tools -> External Tools, Click Add. Fill in the fields as below:
Title | VS2013 Native Tools-Command Prompt |
---|---|
Commands | C:\Windows\System32\cmd.exe |
Arguments | /k "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\VsDevCmd.bat" |
Initial directory | Select what you prefer |
Thus, you can access command prompt under the Tools Menu. The other way to do it is simply opening a Command Console. Then run the batch file “VsDevCmd.bat” in the console. It works the same way.
- Assembly Info and Signing
In the AssemblyInfo.cs file, replace the following lines:
[assembly: ComVisible(true)]
[assembly: AssemblyDelaySign(false)]
Then, select the project, open Properties. In the Signing tab, choose the SNK file.
- Register DLL for COM Interop
Open a Command Console as Administrator, run the command prompt:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe XXX.dll /tlb:XXX.tlb /codebase
My .NET framework version is v4.0.30319.
- Marshaling
This MSDN doc Interop Marshaling talks about Marshaling. In my own usecase, I have met the conversion table below:
.NET | COM client |
---|---|
bool | VARIANT_BOOL |
string | BSTR |
In C++ native codes, to define a BSTR, the code snippet is:
BSTR name = ::SysAllocString(L"The string");