简体   繁体   中英

How to use a WinRT component in c# console(windows form) app?

I have a c++ WinRT component, added to my console app reference. It compiles without any error, but when running app get following error

An unhandled exception of type 'System.TypeLoadException' occurred in mscorlib.dll

Additional information: Could not find Windows Runtime type 'ProcessorInfoComponent.ProcessorInfoProvider'. my error

This is my code:

.h file :

#pragma once

namespace ProcessorInfoComponent
{
public ref class ProcessorInfoProvider sealed
{
   public:
      bool IsNeonSupported();
};
}

.cpp file:

#include "pch.h"
#include "ProcessorInfoComponent.h"
using namespace ProcessorInfoComponent;

bool ProcessorInfoProvider::IsNeonSupported()
{
     return IsProcessorFeaturePresent(PF_ARM_VFP_32_REGISTERS_AVAILABLE);
}

and using in c# is: .cs

    static void Main(string[] args)

    {

        var processorInfoProvider = new ProcessorInfoComponent.ProcessorInfoProvider();

        var isNeonSupported = processorInfoProvider.IsNeonSupported();

        Console.WriteLine(isNeonSupported);

    }

this WinRT work very well in windows phone and WPF APP but in windows form and console app not work. thanks.

For future reference, you should read up on the MSDN page for TypeLoadException and you should put a try...catch(Exception ex) around where the error is occuring and look at the ex.message , generally a good way to catch any errors that might be occuring.

In terms of the error you are having, I'm pretty sure that you aren't able to mix WinRT and WinForms/Console apss since they execute in different ways and WinRT is limited, meaning it doesn't include .Net Framework so can't use many of the functions used in WinForms.

Also, the reason it compiles properly is because of the way C# compiles and runs programs. The C# compiler compiles the code into a Module and then into assembly which contains an Intermediate Language and some Metadata . In short, the program compiles because of no syntax errors but hits a runtime error when executing the line var processorInfoProvider = new ProcessorInfoComponent.ProcessorInfoProvider(); .

Check out this website for some more info on how WinRT works. Or this website for some more info on the C# Compiler.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM