使用.NET Core直接从C#调用C ++(主机)方法

编程入门 行业动态 更新时间:2024-10-27 18:29:27
本文介绍了使用.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 ++(主机)方法

本文发布于:2023-11-15 10:43:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1593713.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:主机   方法   NET   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!