Reputation: 11
I want to access information from a C++ project using the Visual Studio SDK and Microsoft.VisualStudio.VCCodeModel namespace. I have created a console application targeting .NET Framework 4.8 and manually added the reference to the Microsoft.VisualStudio.VCCodeModel.dll in Visual Studio 2022. I am getting the solution from a C++ generated project using the template as a reference with the following code:
[STAThread]
static void Main(string[] args)
{
DTE dte = (DTE)Marshal.GetActiveObject("VisualStudio.DTE.15.0");
if (dte != null)
{
CodeModel codeModel = dte.Solution.Item(1).CodeModel;
if (codeModel != null && codeModel.Language == CodeModelLanguageConstants.vsCMLanguageVC)
{
VCCodeModel vcCodeModel = (VCCodeModel)codeModel;
}
}
}
As it is a console application, I am forcing the execution on a single thread using [STAThread]. I am able to load The C++ application launched in Visual Studio 2017 and check if it is a C++ file, but when casting, I get the following error:
Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.VisualStudio.VCCodeModel.VCCodeModel'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{A590E96B-CC8C-48AF-9E8F-7C3FE7865586}' failed due to the following error: Interface not registered (Exception from HRESULT: 0x80040155).
Upvotes: 1
Views: 87
Reputation: 1191
Judging from the error message, it is because the COM interface is not registered correctly. I recommend using the regsvr32 tool to register the DLL:
1: Open a command prompt (as an administrator).
2: Navigate to the directory containing Microsoft.VisualStudio.VCCodeModel.dll.
3: Run the command: regsvr32 Microsoft.VisualStudio.VCCodeModel.dll.
If the DLL is already registered but the problem persists, and you mentioned that you are using Visual Studio 2022, but you are trying to get an instance of VisualStudio.DTE.15.0, which is the version of Visual Studio 2017. You need to update the code to match the corresponding version of Visual Studio 2022: DTE dte = (DTE)Marshal.GetActiveObject("VisualStudio.DTE.17.0");
Upvotes: 0