簡體   English   中英

使用 .NET 核心直接從 C# 調用 C++(主機)方法

[英]Call C++ (host) methods directly from C# using .NET Core

將 .NET 內核嵌入到 C++ 應用程序中,您可以調用托管方法,如本教程中使用此示例所述。 您甚至可以發送一個 function 指針作為托管代碼回調主機的參數。

但是有沒有辦法直接調用非托管方法,而不使用回調? 使用 Mono,您可以使用 P/Invoke 和DllImport("__Internal")來實現此目的,這將直接在主機程序集中搜索符號。 因此,通過這種方式暴露,您可以將 C++ 功能暴露給 C#,並將后者用作腳本語言。 有沒有辦法用 .NET Core 完成同樣的任務?

我通過創建一個入口點然后使用反射調用方法來解決它。

這是一個例子:

using System;
using System.Reflection;

public class MyType
{
    public string CallMe(int i, float f)
    {
        return $"{i} and {f}";
    }
}

class Program
{
    public static string CallArbitraryMethod(string typeName, string methodName, string[] paramNames, object[] arguments)
    {
        // create the type
        var type = Type.GetType(typeName);
        if (type == null) return null;

        // create an instance using the default constructor
        var ctor = type.GetConstructor(new Type[0]);
        if (ctor == null) return null;
        var obj = ctor.Invoke(null);
        if (obj == null) return null;

        // construct an array of parameter types
        var paramTypes = new Type[ paramNames.Length ];
        for(int i=0; i<paramNames.Length; i++)
        {
            switch(paramNames[i].ToUpper())
            {
                case "INT": paramTypes[i] = typeof(int); break;
                case "FLOAT": paramTypes[i] = typeof(float); break;
                // etc.
                default: return null;
            }
        }

        // get the target method
        var method = type.GetMethod(methodName, paramTypes);
        if (method == null) return null;

        // invoke and return
        return (string)method.Invoke(obj, arguments);
    }

    static void Main(string[] args)
    {
        var result = CallArbitraryMethod("MyType", "CallMe", new string[] {"int", "float"}, new object[] {5, 10.5f});
        Console.WriteLine($"{result}");
    }
}

有關此 GitHub 問題的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM