gpt4 book ai didi

C# MSScriptControl 将类传递给函数

转载 作者:太空宇宙 更新时间:2023-11-03 11:20:26 24 4
gpt4 key购买 nike

我在 C# 中使用 MSScriptControl。我想将一个类从脚本传递给主机。简化示例:Javascript:

function Fx(n) {
this.name = n;
}
var fx = new Fx("test");
rfx.DoEffect(fx);

C#:

[ComVisible(true)]
public class Rfx {
public void DoEffect(object fx) {
// Try to read fx.name
}
}

我的问题是:如何从对象(C# 报告为 System.__ComObject)中获取数据。我尝试了提供的技术 here , 但它不起作用:

public void DoEffect(object fx)
{
System.Reflection.FieldInfo[] myFields = fx.GetType().GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
Console.WriteLine("FieldInfo length = " + myFields.Length);
for (int i = 0; i < myFields.Length; i++)
{
Console.WriteLine("The value of {0} is: {1}", myFields[i].Name, myFields[i].GetValue(fx));
}
}

myFields.Length 为 0。

最佳答案

构建 Mangist 的代码,这有效:

using System; 
using System.Runtime.InteropServices;
using ComTypes = System.Runtime.InteropServices.ComTypes;

public class ComHelper
{
public static string GetValue(object comObj, string name)
{
if (comObj == null)
return String.Empty;

if (!Marshal.IsComObject(comObj))
//The specified object is not a COM object
return String.Empty;

IDispatch dispatch = comObj as IDispatch;
if (dispatch == null)
//The specified COM object doesn't support getting type information
return String.Empty;

try
{
int language_id = 0;
int DISPATCH_METHOD = 0x1;
int DISPATCH_PROPERTYGET = 0x2;

int[] displayIDs = new int[1];
Guid empty = Guid.Empty;
string[] names = new string[] { name };
dispatch.GetIDsOfNames(ref empty, names, names.Length, language_id, displayIDs);
System.Runtime.InteropServices.ComTypes.DISPPARAMS dspp = new System.Runtime.InteropServices.ComTypes.DISPPARAMS();
System.Runtime.InteropServices.ComTypes.EXCEPINFO ei = new System.Runtime.InteropServices.ComTypes.EXCEPINFO();
IntPtr[] arg_err = new IntPtr[10];
object result;
if (1 == displayIDs.Length)
{
dispatch.Invoke(displayIDs[0], ref empty, language_id, (ushort)(DISPATCH_METHOD | DISPATCH_PROPERTYGET), ref dspp, out result, ref ei, arg_err);
return result.ToString();
}
return String.Empty;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return String.Empty;
}
}
}

我之前在 C++ 中完成过此操作,因此我可以将代码复制过来,但我仍然对 C# 有所涉猎。

关于C# MSScriptControl 将类传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11211973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com