使用.NET Core直接从C#调用C ++(主机)方法 [英] Call C++ (host) methods directly from C# using .NET Core

查看:373
本文介绍了使用.NET Core直接从C#调用C ++(主机)方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将.NET Core嵌入C ++应用程序中,您可以调用托管方法,如

Embedding .NET Core into a C++ application you can call managed methods like it's described in this tutorial with this sample. You can even send a function pointer as a parameter for the managed code to call back into the host.

但是有什么方法可以在不使用回调的情况下直接调用非托管方法?使用Mono,可以使用P/Invoke和DllImport("__Internal")来实现此目的,它们将直接在主机部件中搜索符号.因此,通过这种方式,您可以将C ++功能公开给C#,并将后者用作脚本语言. 是否可以通过.NET Core完成相同的操作?

But is there any way to invoke unmanaged methods directly, without using callbacks? With Mono, you can achieve this using P/Invoke and DllImport("__Internal") which will search for the symbols in the host assembly directly. So in this way expose you can expose your C++ functionality to C# and use the later as a scripting language. Is there a way to accomplish the same with .NET Core?

推荐答案

我已经解决了这一问题,方法是创建一个入口点,然后使用Reflection调用方法.

I've solved it by creating an entry point and then calling the methods using Reflection.

这是一个例子:

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问题的更多信息 .

More information on this GitHub issue.

这篇关于使用.NET Core直接从C#调用C ++(主机)方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆