动态调用本机库

时间:2014-11-27 08:05:21

标签: .net visual-studio c++-cli

我试图从本机c ++ dll调用函数,由名称,参数和返回类型给出。 现在我有问题为编组进行委托。

我这样做:

Object^ Invike(Type^ Return_Type, array<Type^>^ Types, array<Object^>^ Parameters)
{
 //demo data
 Return_Type=long::typeid;
 Types = gcnew array < Type^ > {String::typeid, int::typeid};
 Parameters = gcnew array < Type^ > {"test",1};

 //parameters initializated in class constructor
 //IntPtr DLL_File = Native_Dll::LoadLibrary(Dll_Name);
 //IntPtr Init_Function = Native_Dll::GetProcAddress(DLL_File, "_McamGetNumberofCameras@0");

 DynamicMethod^ Function_Prototype = gcnew DynamicMethod("test", Return_Type, Types);

 //ArgumentException exception in this line
 Delegate^ Function_Delegate = Marshal::GetDelegateForFunctionPointer(Init_Function, Function_Prototype->GetType());

 Object^ Result = Function_Delegate->DynamicInvoke(Parameters);

 return Result;
}

在创建Function_Delegate时,我有一个例外

An exception of type 'System.ArgumentException' occurred in mscorlib.dll but was not handled in user code
Additional information: Type must derive from Delegate.

有可能做我想做的事吗?

还有其他方法吗?

我期待Func&lt;&gt;模板也,但不是真正了解如何使用它。

1 个答案:

答案 0 :(得分:0)

我确实通过使用AssemblyBuilder制作动态包装器来解决问题。 这是代码片段。

AssemblyName^ Delegate_Class_Name = gcnew AssemblyName("Dynamic_Class");

AssemblyBuilder^ Delegate_Class = AppDomain::CurrentDomain->DefineDynamicAssembly(Delegate_Class_Name, AssemblyBuilderAccess::RunAndSave);

ModuleBuilder^ Delegate_Class_Module = Delegate_Class->DefineDynamicModule(Delegate_Class_Name->Name, Delegate_Class_Name->Name + ".dll");

TypeBuilder^ Delegate_Class_Type = Delegate_Class_Module->DefineType("Dynamic_Class_Type", TypeAttributes::Public);

//a can add as much functions from native dll as a need
MethodBuilder^ Delegate_Function = Delegate_Class_Type->DefinePInvokeMethod(
        "_McamGetNumberofCameras@0",
        Dll_Name,
        MethodAttributes::Public | MethodAttributes::Static | MethodAttributes::PinvokeImpl,
        CallingConventions::Standard,
        long::typeid,
        Type::EmptyTypes,
        CallingConvention::Winapi,
        CharSet::Ansi);

Delegate_Function->SetImplementationFlags(Delegate_Function->GetMethodImplementationFlags() | MethodImplAttributes::PreserveSig);

Type^ Delegate_Type = Delegate_Class_Type->CreateType();

MethodInfo^ Delegate_Instace = Delegate_Type->GetMethod("_McamGetNumberofCameras@0");

//now i can just run it.
int result= (int) Delegate_Instace->Invoke(nullptr, nullptr);