以下是我總結出的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#的命名空間,後一個是類的名稱。