【问题标题】:How to export C# dll method/functions to use it in C++ [duplicate]如何导出 C# dll 方法/函数以在 C++ 中使用它 [重复]
【发布时间】:2015-08-31 12:23:21
【问题描述】:

我已经用C#完成了我的部分编码,下面给出一个小方法

 public  static unitdefn GetUnit(XmlDocument doc)
    {

        XmlNodeList nodeList1 = (XmlNodeList)doc.DocumentElement.SelectNodes("//UnitDefinitions/Unit");
        int countdefn = nodeList1.Count;
        unitdefn[] arrunt = new unitdefn[countdefn];
        if (countdefn != 0)
        {

            int i = 0;
            foreach (XmlNode node in nodeList1)
            {
                XmlAttribute att = node.Attributes["name"];
                if (att != null)
                {
                    string idu = node.Attributes["name"].Value;
                    //System.Console.WriteLine(id1);
                    arrunt[i].name = idu;
                }
                i++;
            }

        }
        return arrunt[0];
    }

并且我希望在我的 C++ 项目中使用此方法,并且我已经完成了如下所示

int  xmlRead()
{

int x=1,s=1;
char xmldllpath[1000]="//dllpath";
HMODULE h = LoadLibrary(xmldllpath);

if (!h) {
    printf("error: Could not load %s\n", xmldllpath);
    return 0; // failure
}

getAdr(&s, h, "GetUnit");
}

dll 加载成功,但未获取该方法 任何具体的方法来做到这一点

【问题讨论】:

  • 将 C# 方法“导出”到 C++ 存在一个非常大的问题 - C# 代码全部在 .Net 虚拟机中运行 - 后台总是在执行 JIT、终结/垃圾收集等。在支持从 C++ 代码直接调用的同时如何提供该环境?答案要复杂得多。

标签: c# c++ unmanaged dllexport


【解决方案1】:

不要。不支持从 C# 导出方法。手动编辑发出的程序集几乎是不可能的,但真的 - 不要。

您可以使用一些合适的解决方案:

  • 使用 C++/CLI 项目将托管方法公开给非托管代码
  • 使用 COM(.NET 基本上是 COM 2.0,所以这很容易;在 C++ 端也很容易使用)
  • 在初始化时将委托传递给非托管代码,并在需要时调用它
  • 使用其他一些进程间通信方法(例如命名管道、TCP...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-06
    相关资源
    最近更新 更多