我现在用C#做了一个WINFORM的客户端
然后现在要通过一个中间件做为接口,与底层进行数据交换而这个中间件是一个用C++写成的DLL文件,不能直接在项目里引用加入
我看到网上说在C#文件里使用[Dllimport]然后再声明DLL文件中的方法但是现在我这个DLL文件中的方法全是在类里面,我如何使用这个类里的属性和方法呢?或者说把这个DLL封装成COM?那又如何封装呢?、各位大侠帮忙啊,网上搜了一天了,眼睛都快瞅瞎了

解决方案 »

  1.   

    由于c++中的函数接口好多都可能定义成位指针,而c#中只有在声明为unsafe code中才能够使用指针。如果想让c++的DLL支持在C#中调用,那么在C++接口的声明中需要使用下面的这种格式: extern "C" __declspec(dllexport) void __stdcall popMessage(char* message) { MessageBox(NULL, message, "C message from C#!", MB_OK); } 并且在c#类声明中使用如下的导入编译好的DLL,例如: [ DllImport( "test.dll", CallingConvention=CallingConvention.Cdecl )] public static extern void Message(string theMessage); 当然你可以从一个DLL中导入多个方法的声明,例如: [ DllImport( "test.dll", CallingConvention=CallingConvention.Cdecl )] public static extern void Func1(string theMessage); [ DllImport( "test.dll", CallingConvention=CallingConvention.Cdecl )] public static extern void Func2(string theMessage); [ DllImport( "test.dll", CallingConvention=CallingConvention.Cdecl )] public static extern void Func3(string theMessage); 然后你可以在你的c#类中调用上面声明的方法。 
    *********************************************************************
    我也不是很清楚  给你转一个吧
      

  2.   

    引用: using System.Runtime.InteropServices;
            [DllImport("Kernel32")]                    //读取动态库文件
            public static extern int GetProcAddress(int handle, String funcname);
            [DllImport("Kernel32")]
            public static extern int LoadLibrary(String funcname);
            [DllImport("Kernel32")]
            public static extern int FreeLibrary(int handle);
            [DllImport("HmPark.dll")]                  //声明C++中的接口函数,  其中 HmPark 为你的动态库文件名
            public static extern double GetStdCharge(UInt32 time_In, UInt32 time_Out);        private int huser32 = 0;
            private void CountCharge()
            {
        double dCharge = 0;
                try
                {
                    huser32 = LoadLibrary("HmPark.dll");        //载入动态库
                    dCharge = GetStdCharge(time_In, time_Out); //调用 C++ 中的接口函数
                }
                catch (Exception ex)
                {
                    MessageBox.Show("调用出错: " + ex.Message, "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    try
                    {
                        Inspect.FreeLibrary(huser32);                          //释放动态库文件, 否则会弹出异常
                    }
                    catch (Exception ee)
                    {
                        MessageBox.Show("释放出错: " + ee.Message, "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
      

  3.   

    如果是dll中的类的方法,你再好好找找吧。
      

  4.   

    是类里面的函数是不能够直接调用的, 可以在类外面封装一个函数, 通过这个封装的函数使用类内部的函数. 将这个函数导出, 你在C#中调用这个函数.DLL导出类的问题, 参考:
    http://blog.csdn.net/hjyhh/archive/2008/03/03/2142402.aspx
      

  5.   


    你说的这种方法我考虑过,确实是可以使用里面的函数
    但是也还是有问题的,比如说我在这个DLL文件里定义了一个类,就叫MyTest吧
    然后有函数的返回值就是这个类,这种的就不能直接使用吧