C# & C++ Load MfcDll

来源:互联网 发布:黑马程序员视频教程h5 编辑:程序博客网 时间:2024/06/05 06:34

//MfcDll:

BSTR CMyMFCdllApp::MyDllTest(TCHAR* x)
{
    CString str(x);
    str+="_经过MFC处理的数据";
    return str.AllocSysString() ;
}

int CMyMFCdllApp::MyDllNumTest(int x)
{
 int y=20;
 return y*x;
}

byte* CMyMFCdllApp::MyDllByteTest(int ByteLenght)
{
   byte *bx=new byte[ByteLenght];
   for(int i=0;i<ByteLenght;i++)
   {
    bx[i]=212;
   }
   return bx;
}
//MyMFCdll.def

; MyMFCdll.def : 声明 DLL 的模块参数。

LIBRARY      "MyMFCdll"

EXPORTS
      MyDllStringTest
      MyDllNumTest
      MyDllByteTest
    ; 此处可以是显式导出

     DllCanUnloadNow     PRIVATE
     DllGetClassObject   PRIVATE
     DllRegisterServer   PRIVATE
     DllUnregisterServer PRIVATE

 

 

C#:

        using System.Runtime.InteropServices ;

        [DllImport("MyMFCdll.dll", EntryPoint = "MyDllStringTest", CharSet = CharSet.Unicode)]
        private static extern IntPtr  MyDllStringTest(string x);

        [DllImport("MyMFCdll.dll", CharSet = CharSet.Unicode)]
        private static extern int MyDllNumTest(int x);

        [DllImport("MFCdll.dll", EntryPoint = "MyDllByteTest", CharSet = CharSet.Unicode)]
        private static extern IntPtr MyDllByteTest(int ByteLenght);

        private void button4_Click(object sender, EventArgs e)
        {
//string:
            MessageBox.Show(Marshal.PtrToStringBSTR(MyDllStringTest("中文123abc")));
//Num:           
            MessageBox.Show(MyDllNumTest(100).ToString());
//Byte:
            int ByteLenght = 1000;
            byte[] bx = new byte[ByteLenght];
            IntPtr p= MyDllByteTest(ByteLenght);

            for (int i = 0; i < ByteLenght; i++)
            {
                bx[i] = Marshal.ReadByte(p, i);
            }
        }

 

C++ :

 typedef BSTR (WINAPI *MyFunC)(TCHAR*);
 HINSTANCE hDllInst = ::LoadLibrary(_T("MyMFCdll.DLL"));
 MyFunC DllFun = (MyFunC)::GetProcAddress(hDllInst,"MyDllTest");
 ::AfxMessageBox(DllFun(_T("MFCDLL动态调用")));
 ::FreeLibrary(hDllInst);

 

 

//c# Load MSDOS RegDll

            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();

            p.StandardInput.WriteLine(@"MD C:/123");
            p.StandardInput.WriteLine(@"subst U: C:/123");

            p.Close();

 

//c# Auto RegDll

        using System.Runtime.InteropServices ;

 

        [DllImport("MyMFCdll2.dll", EntryPoint = "DllUnregisterServer")]
        static extern int DllUnregisterServer();

 

        [DllImport("MyMFCdll2.dll", EntryPoint = "DllRegisterServer")]
        static extern int DllRegisterServer();