c# - 在 C++Builder 应用程序中动态加载 C# .NET 程序集

标签 c# c++ dll .net-assembly c++builder

我有一个使用 RAD Studio 开发的 C++ Windows 应用程序 (C++Builder) XE4。它有一些插件,这些插件是用 this technique 动态加载的 DLL(总是用 RAD Studio 编写的)。 .

现在,在其中一个插件中,我需要反射功能。虽然我似乎无法用 C++ 实现它们(在我无法修改的第三方 COM DLL 上需要反射),但我决定用 C# 重写这个插件(它具有强大的反射功能),从而创建.NET 程序集

我知道我应该通过 COM 公开程序集,但我不能(我们不想改变主应用程序加载所有 DLL 的方式)。

我的目标是动态加载 .NET 程序集并调用它的函数(例如这里我们调用 SetParam 函数),就像我做的那样其他插件。

//load DLL
HINSTANCE handleDll = LoadLibraryW("C:/Path/to/the/assembly.dll");
//get reference to the function
void* ptr = GetProcAddress(handleDll, "_SetParam");
ptr_SetParam ptrFunc = reinterpret_cast<ptr_SetParam>(ptr);
//invoke function
int result = (*ptrFunc)(String("mykey").c_str(), String("myvalue").c_str());

其中 ptr_SetParam 定义为

typedef int(*ptr_SetParam)(const wchar_t*, const wchar_t*);

有办法吗?

最佳答案

感谢@HansPassant 的评论,我找到了一种方法。

我创建了以下 Visual Studio 项目。

MyDllCore .NET 程序集项目,用 C# 或任何其他 .NET 语言编写。在这里,我有如下所示的托管类,其中实现了程序集的真正逻辑。

using System;
using System.Collections.Generic;
//more usings...

namespace MyNamespace
{
    public class HostDllB1
    {
        private Dictionary<string, string> Parameters = new Dictionary<string, string>();

        public HostDllB1()
        {
        }

        public int SetParam(string name, string value)
        {
            Parameters[name] = value;
            return 1;
        }
    }
}

MyDllBridge DLL 项目,用 C++/CLI 编写,带有 /clr 编译器选项。它只是一个“桥梁”项目,它依赖于 MyDllCore 项目并且只有一个 .cpp 或 .h 文件,如下所示,我将方法从加载 DLL 的程序映射到 .NET 程序集中的方法.

using namespace std;
using namespace System;
using namespace MyNamespace;
//more namespaces...

#pragma once
#define __dll__
#include <string.h>
#include <wchar.h>
#include "vcclr.h"
//more includes...

//References to the managed objects (mainly written in C#)
ref class ManagedGlobals 
{
public:
    static MyManagedClass^ m = gcnew MyManagedClass;
};

int SetParam(const wchar_t* name, const wchar_t* value) 
{
    return ManagedGlobals::m->SetParam(gcnew String(name), gcnew String(value));
}

最后,我有一个 C++Builder 程序,它加载 MyDllBridge.dll 并使用它的方法调用它们,如下所示。

//load DLL
HINSTANCE handleDll = LoadLibraryW("C:/Path/to/the/MyDllBridge.dll");
//get reference to the function
void* ptr = GetProcAddress(handleDll, "SetParam");
ptr_SetParam ptrFunc = reinterpret_cast<ptr_SetParam>(ptr);
//invoke function
int result = (*ptrFunc)(String("mykey").c_str(), String("myvalue").c_str());

关于c# - 在 C++Builder 应用程序中动态加载 C# .NET 程序集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32503650/

相关文章:

c# - 是否可以同时使用线程并发和并行?

带有授权和 JSON 数据的 C# HttpClient 发布 - 401 未经授权

c++ - 从文本文件读取到数组

c# - Crystal Reports 可以缩放以适合页面吗

c# - 如何获取 IServiceCollection 扩展中的依赖项

c# - 在 C# 类库中使用 C++ 非托管类

c++ - WinAPI SendInput 代码问题

python - 使用 ctypes 模块访问用 C 编写的 DLL 时出错

java - 如何在java中访问C++库(DLL)的方法

python - COM 和 Windows DLL 之间有什么关系?