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(""));
          // 自定义处理方法
        }
    }
}


你可能感兴趣的:(C++调用dll C#调用dll)