[英]Call C++ (host) methods directly from C# using .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.