将.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 ++(主机)方法
发布评论