C#環(huán)境:VS2008 Mablab:7.10.1(R2010a) 一、C#端示范 using System; using System.Collections.Generic; using System.Linq; using System.Text; //添加com及數(shù)據(jù)庫引用 using System.Runtime.InteropServices; namespace MatlabClass { [Guid("5E019C5C-C021-4D6E-BEDE-3120525A15D8")] //工具->創(chuàng)建GUID->... public interface Mat_I { //沒有[DispId(*)]也可以 [DispId(0)] //返回常數(shù),在Open Selection中可見. string GetName(); [DispId(1)] //在Open Selection中不可見 float Add(float a, float b); } //自定義ProgID:將MatlabCS類的注冊名改變,也可以不改變,則注冊名稱為"命名空間.類名"(見MatlabCS2) [ProgId("MatlabID")] [ClassInterface(ClassInterfaceType.None)] public class MatlabCS:Mat_I { /// <summary>獲取本類的名稱</summary> /// <returns>本類的名稱</returns> public string GetName() { return "I am MatlabCS"; } /// <summary>浮點(diǎn)數(shù)加法 </summary> /// <param name="a">加數(shù)</param> /// <param name="b">加數(shù)</param> /// <returns>和</returns> public float Add(float a, float b) { return a + b; } } public interface Mat_I2 { [DispId(0)] //在Open Selection中不可見? 未與[ClassInterface(ClassInterfaceType.None)]配匹 string GetName2(); [DispId(1)] float Add2(float a, float b); } public class MathlabCS2:Mat_I2 //COM 的注冊名為MatlabClass.MatlabCS2 { public string GetName2() { return "I am Number 2";} public float Add2(float a, float b) { return -(a+b);} } } 修改AssemblyInfo.cs [assembly: ComVisible(true)] 編譯注冊 MatlabClass屬性 為COM互操作注冊 (或者在外面注冊也可) C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\regasm MatlabClass.dll /tlb: MatlabClass.tlb /codebase OK 總結(jié):C#制作COM(DLL)是常規(guī)做法,唯一要注意的是COM的注冊名(ProgID) 二、Matlab端 >> h=actxserver('MatlabID') h = COM.MatlabID >> h=actxserver('MatlabClass.MathlabCS2') h = COM.MatlabClass_MathlabCS2 -----注意注冊名(ProgID),而不是DLL的路徑名 其他的h.get等不再說明 三、關(guān)于64位機(jī)的注意事項(xiàng) 應(yīng)用一段原文: Reinstall MATLAB as a 32-bit program.Your 32-bit driver will work with a 64-bit OS, but MATLAB can't be 64-bit for actxserver to load a 32-bit dll. Under 32 bit environment, configure automatic regasm: Project properties >Build tab > check "Register for COM Interop" But this will fail under 64 bit (i.e. Build target x64" with the following error message: "File <path to assembly> is not a valid assembly" In an attempt to resolve this, uncheck "Register for COM Interop" from Project properties. Then run the following command after build (or add post-build command): C:\WINDOWS\Microsoft.NET\Framework64\v2.0.50727\regasm SQLCmdRunner.dll /tlb: SQLCmdRunner.tlb ----在64位機(jī)上 Uncheck“為COM互操作注冊”項(xiàng)。在64為機(jī)器上需要要用”Framework64“下的regasm進(jìn)行顯性注冊 四、其他 1、 com注冊信息全部存在于注冊表的HKEY_CLASSES_ROOT鍵下,最主要的是CLSID子健。在CLS子鍵下,列除了當(dāng)前機(jī)器上所有組件的信息。 2、interface可以簡化,如果沒有在接口中聲明,即使該方法(屬性)為公有,也不能正常導(dǎo)出到COM。但他們可以被別的.NET程序所使用; |
|