c#中寫的dll直接是不能被pb調用的,只有寫成com組件才可以調用,所以用c#寫dll時要註意。
1、c#2005中新建項目,類型為類庫,項目名為AddCom確定。
配置:右鍵點擊解決方案資源管理器中的AddCom,選擇“屬性”,選擇“生成”,選擇“為COM Interop註冊(_P)”
2、打開AssemblyInfo.cs文件,設置[assembly: ComVisible(true)],如果不改則不能被其他程序調用
3、編寫com組件會用到guid(全球唯壹ID),編寫com組件必須要用到。c#會默認生成壹個放在AssemblyInfo.cs,如沒有生成,網上下壹個生成guid的軟件,有很多呢。
4、c#中源代碼如下,按如下方法編寫代碼後生成工程,/bin/release中得到AddCom.dll。
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace AddCom
{
[Guid("298D881C-E2A3-4638-B872-73EADE25511C")]
public interface AddComInterface
{
[DispId(1)]
int iadd(int a, int b);
}
[Guid("2C5B7580-4038-4d90-BABD-8B83FCE5A467")]
[ClassInterface(ClassInterfaceType.None)]
public class AddComService : AddComInterface
{
public AddComService()
{
}
public int iadd(int a, int b)
{
int c = 0;
c = a + b;
return c;
}
}
}
5、dos下利用 e:\regasm AddCom.dll 命令註冊com組件,可以理解為非.net平臺下的regsvr32註冊dll組件。提示註冊成功即可。
6、pb11中利用ole調用來調用com組件,註意,此com組件無法用create ole control的browse查看到,只能利用如下的方法直接動態調用。
integer li_a,li_b,li_total
//----------註冊c#生成的com組件------------
OleObject ole_AddCom
ole_AddCom = Create OLEObject
li_rc = ole_AddCom.ConnectToNewObject("AddCom.AddComService") //AddCom為c#中namespace,AddComService為c#中namespace中的class
if li_rc <> 0 then
MessageBox("ConnectToNewObject", string(li_rc) )
return
end if
//----------調用com組件中的函數--------------
li_total = ole_AddCom.iadd(li_a, li_b) //iadd為c#中namespace(AddCom為c)中class(AddComService為c)中的函數(iadd())