遗忘海岸

江湖程序员 -Feiph(LM战士)

导航

PB调用.NET代码的两个入口函数

定义如下两个函数,用来调用.Net的窗口与方法,只支持string类型的参数

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Windows.Forms;
namespace DotNetExt
{
    public class Util
    {
        public string RunForm(string assembly, string type, string args, int hasArgs, int isDialog)
        {
           
            var t=Assembly.LoadFrom(assembly + ".dll").GetType(type,true);
            Form frm=null;
            if (hasArgs > 0)
            {
                frm = Activator.CreateInstance(t, args) as Form;
            }
            else
            {
                frm = Activator.CreateInstance(t) as Form;
               
            }

            if (isDialog > 0)
            {
                frm.ShowDialog();
            }
            else
            {
                frm.Show();
            }
        
            return "";
        }

        public string InvokeMethod(string assembly, string type,string method, string args, int hasArgs,int isInstance)
        {
            var t = Assembly.LoadFrom(assembly + ".dll").GetType(type, true);
            object target = null;
            if (isInstance > 0)
            {
                target= Activator.CreateInstance(t);
            }
            if (hasArgs > 0)
            {
                return t.InvokeMember(method, BindingFlags.Default | BindingFlags.InvokeMethod, null, target, new object[] { args }).ToString();
            }
            else
            {
                return t.InvokeMember(method, BindingFlags.Default | BindingFlags.InvokeMethod , null, target,null).ToString();
            }


        }
    }
}

 

注意:

1.第一次将InvokeMethod定义成Invoke时发现找不到定义,提示错误时找不到"invoke"的函数定义(第一个字符小写)

2.直接使用var t= Type.GetType(type +"," + assembly,true) 时在.Net中可以自动加载目录下的dll,而在PB中必需Assembly.LoadFrom("xxx.dll")

3.返回的string类型在pb中作为Any类型,需要使用string()进行转换。

//===PB中的调用代码============= 

View Code
 OLEObject util
 long conn_status //conn_status为0时是正常的,其他值的具体含义看帮助文档

 util = Create OLEObject
 conn_status=util.ConnectToNewObject ("DotNetExt.Util")
messagebox("",string(conn_status))

util.RunForm("LibA", "LibA.frmMain", "传入参数", 1, 1)

messagebox("",string(util.InvokeMethod("LibA", "LibA.A", "TestA", "AA", 1, 1)));
messagebox("",string(util.InvokeMethod("LibA", "LibA.A", "TestB", "BB", 1, 0)));
messagebox("",string(util.InvokeMethod("LibA", "LibA.A", "TestC", "cc",0, 1)));

 util.disconnectobject( );
 
 destroy util;


 

posted on 2012-05-29 18:28  遗忘海岸  阅读(704)  评论(0编辑  收藏  举报