C ++ / CLI在运行时显式加载托管DLL(相当于UnLaged的LoadLibrary)

时间:2010-06-23 14:36:50

标签: .net dll c++-cli loadlibrary

问题1:

有没有办法在运行时显式加载库,而不是在C ++ / CLI中的编译时。目前我在编译时使用.NET“添加引用”。 我想明确加载一个托管的DLL。是否有与LoadLibrary等效的.NET?

更新:感谢Randolpho

汇编::来自MSDN

的LoadFrom示例
Assembly^ SampleAssembly;
SampleAssembly = Assembly::LoadFrom( "c:\\Sample.Assembly.dll" );
// Obtain a reference to a method known to exist in assembly.
MethodInfo^ Method = SampleAssembly->GetTypes()[ 0 ]->GetMethod( "Method1" );
// Obtain a reference to the parameters collection of the MethodInfo instance.
array<ParameterInfo^>^ Params = Method->GetParameters();
// Display information about method parameters.
// Param = sParam1
//   Type = System::String
//   Position = 0
//   Optional=False
for each ( ParameterInfo^ Param in Params )
{
   Console::WriteLine( "Param= {0}", Param->Name );
   Console::WriteLine( "  Type= {0}", Param->ParameterType );
   Console::WriteLine( "  Position= {0}", Param->Position );
   Console::WriteLine( "  Optional= {0}", Param->IsOptional );
}

问题2:

如果Assembly :: LoadFrom是LoadLibrary的.NET等价物。 GetProcAddress的等价物是什么?如何为方法创建FunctionPointers?

更新:来自MSDN

的MethodBase.Invoke
using namespace System;
using namespace System::Reflection;

public ref class MagicClass
{
private:
    int magicBaseValue;

public:
    MagicClass()
    {
        magicBaseValue = 9;
    }

    int ItsMagic(int preMagic)
    {
        return preMagic * magicBaseValue;
    }
};

public ref class TestMethodInfo
{
public:
    static void Main()
    {
        // Get the constructor and create an instance of MagicClass

        Type^ magicType = Type::GetType("MagicClass");
        ConstructorInfo^ magicConstructor = magicType->GetConstructor(Type::EmptyTypes);
        Object^ magicClassObject = magicConstructor->Invoke(gcnew array<Object^>(0));

        // Get the ItsMagic method and invoke with a parameter value of 100

        MethodInfo^ magicMethod = magicType->GetMethod("ItsMagic");
        Object^ magicValue = magicMethod->Invoke(magicClassObject, gcnew array<Object^>(1){100});

        Console::WriteLine("MethodInfo.Invoke() Example\n");
        Console::WriteLine("MagicClass.ItsMagic() returned: {0}", magicValue);
    }
};

int main()
{
    TestMethodInfo::Main();
}

2 个答案:

答案 0 :(得分:1)

您说托管 DLL吗?那你想要Assembly::Load

答案 1 :(得分:0)

查看http://www.informit.com/articles/article.aspx?p=25948以获取有关反射的信息。可能是你正在寻找的机票(不知道更多的问题,很难说)

它有一整节关于动态加载程序集并探测它们以找出方法和属性等等。