C#創建COM供PB調用

 PB9(包括 PB9)以前的版本都不能訪問VS.Net創建的基於Net FrameWork下的程序,除非將程序編譯成COM,PB才能正常調用。
    以下是我總結出的C#將類庫編譯成COM所需要的步驟:
1.創建一個類庫程序;
2.在程序裏添加using System.Runtime.InteropServices;
3.創建一個公用的函數,以供PB調用;
4.啓動命令窗口;
5.生成snk文件:
    sn -k test2.snk
6.將cs文件編譯成dll文件:
    csc /t:library /keyfile:test2.snk /out:test2.dll test2.cs
如果在程序中添加的引用不屬於System下的,例如:Microsoft.VisialBasic.dll,編譯的語句改爲:
    csc /t:library /keyfile:test2.snk /out:test2.dll /r:Microsoft.VisualBasic.dll test2.cs
7.註冊COM:
    regasm test2.dll /tlb:test2.tlb /codebase

C#例子的全部代碼如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace test2
{
    public class test2
    {
        public int ShowMsg(out int a1,out string a2)
        {
            a1 = 200;
            a2 = "message";
            return 100;
        }
    }
}

    PB調用的方法如下:
OLEObject test2
long ll_status
integer li_return
long ll_a1
string ls_a2
//創建OLEObject對象
test2 = Create OLEObject
ll_status= test2.ConnectToNewObject("test2.test2")
if ll_status=0 then 
    //調用類內的公共函數
    li_return = test2.ShowMsg(ref ll_a1,ref ls_a2)
    messagebox(string(ll_a1)+" "+ls_a2,string(li_return))
end if
//釋放資源
test2.DisConnectObject()

特別說明:
ll_status= test2.ConnectToNewObject("test2.test2")語句中的兩個test2,前一個是C#的命名空間,後一個是類的名稱。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章