Search code examples
interopc++-clicom-interoptypelib

Why exception occured at LoadTypeLibEx System.ArgumentException: Value does not fall within the expected range?


I am loading type library in C++/CLI. In C# its loading successfully but it's giving again and again following exception in managed C++/CLI.

exception occured at LoadTypeLibEx System.ArgumentException: Value does not fall within the expected range

at LoadTypeLib(String strTypeLibName, ITypeLib typeLib)

Here's a PInvoke Signature:

[DllImport("oleaut32.dll", CharSet = CharSet::Unicode, PreserveSig = false)]
static void LoadTypeLib(String^ strTypeLibName, [MarshalAs(UnmanagedType::Interface)] [Out] System::Runtime::InteropServices::ComTypes::ITypeLib^ typeLib);

My code:

ITypeLib^ oTypeLib;
LoadtypeLib(TLB, oTypeLib);

I am stuck here. Kindly give me way around to get rid of this exception.

Regards Usman


Solution

  • With C++/CLI, usually you want to call API functions using a prototype from the public header file, not by writing a p/invoke declaration yourself. The compiler will use either C++ interop or p/invoke depending on whether you're using /clr or /clr:pure.

    In any case, the second argument should be pass-by-reference. In C#, that'd use the out keyword. In C++/CLI, the syntax for an out argument is:

    void func([Out] Type% arg1);
    

    In your case, perhaps

    static void LoadTypeLib(String^ strTypeLibName, [Out] ComTypes::ITypeLib^% typeLib);