C++調用dll C#調用dll

c++調用dll方法

typedef BSTR(__stdcall *GetEncrypt)(const char* a1, const char* a2);

int main(int argc, char *argv[], char *envp[])
{
    HINSTANCE hDLL = LoadLibrary(("MyDll.dll")); //加載dll文件 
    if (hDLL != NULL)
    {
        GetEncrypt fp1 = GetEncrypt(GetProcAddress(hDLL, (LPCSTR)1)); //得到dll中的第一個函數
        if (fp1 != NULL)
        {
                        // 自定義處理方法
        }
        else
        {
            cout << "Cannot Find Function " << "GetEncrypt" << endl;
        }

        FreeLibrary(hDLL);
    }
    else
    {
        std::cout << "Cannot Find " << "MyDll" << std::endl;
    }
    return 1;
}

如果運行時提示找不到dll,或者加載失敗,可以修改程序屬性-常規-項目默認值-字符集 改成使用多字節字符集

C# 調用dll 方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

namespace DllDemo2
{
    class Program
    {
        [System.Runtime.InteropServices.DllImport("MyDll.dll", CharSet = CharSet.Unicode, SetLastError = true, CallingConvention = CallingConvention.Cdecl, EntryPoint = "GetEncrypt")]
        [return: MarshalAs(UnmanagedType.BStr)]

        static extern string GetEncrypt(IntPtr pwd, IntPtr acc);

        static void Main(string[] args)
        {
            var test = GetEncrypt(Marshal.StringToHGlobalAnsi("111111"), Marshal.StringToHGlobalAnsi(""));
          // 自定義處理方法
        }
    }
}


?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容