QT调用C#写的Dll

参见:

https://blog.csdn.net/weixin_42420155/article/details/81060945

C#写的dll是没有dllMain入口函数的,是一种中间语言,需要.Net运行时进行做本地化工作,因此如果要调用C#写的dll,需要依赖.Net运行时,然而Qt中还无法直接调用.Net运行时,最好的方式是能够在Qt中直接调用C#dll的函数,但是Qt明显只能调用C++写的dll,所以就只能通过编写一个C++的dll导出接口供Qt调用,这个C++编写的dll对C#写的dll进行封装,这个C++的dll可以采用/CLR方式对C#编写的dll进行引用的,即将C++编写的dll中生成的.lib文件供Qt进行链接,由于该接口符合C++规范,所以Qt可以链接到对应的C++编写的dll。
---------------------
编译环境为:VS2010

C++ 中要加 extern "C"才行,不然生成后的DLL使用DLL查看器可以发现函数名前莫名的会多个?号。

// CppDll.h

#pragma once
using namespace System::Reflection;

using namespace System;

extern "C" __declspec(dllexport) int api_add(int a, int b)
{
CSharpDll::CSharpClass obj;
return obj.add(a, b);
}
extern "C" __declspec(dllexport) void api_showBox(const char* content)
{
CSharpDll::CSharpClass obj;
String^ str = gcnew String(content);
obj.showBox(str);
}

--------------

其他相同

QT引用方式,三种

第一种、引用lib文件进行编译

1、pro文件加  

  LIBS += -LF:/QT5.11/TestCSharpDll -lCppDll

2、在CPP中声名 

extern "C" __declspec(dllexport) int api_add(int a, int b);
extern "C" __declspec(dllexport) void api_showBox(const char* content);

3、然后就可以直接使用了

qDebug()<<"C# DLL add:"<<api_add(8,5);

第二种、直接C++方式调用C++DLL

  //纯C++方式调用
  typedef int(CALLBACK *funci)(int,int);
  HINSTANCE hdll=LoadLibrary(L"MyDll2.dll"); //L指宽字符串,若不写L,则会出现错误,详情请自查
  funci t3=(funci)GetProcAddress(hdll,"_ZN6MyDll26lllsumEii");//这里原先写的函数名为“sum”但是QT编译后的DLL,通过DLL查看器会发现 函数名变了,所以调用时需要使用DLL查看器得到的这个名字才行,不然无法调用成功。
  qDebug()<<"C++ mode:"<<t3(9,9);

第三 种、QT的显示调用

    //MyDll test-----------------------
    typedef  int (* fun)(int,int );
    QLibrary mylib("MyDll.dll");
 
    //qDebug()<<"in dll function";
 
    if(mylib.load())
    {
        //qDebug()<<"加载DLL OK";
        fun fun1  = (fun)mylib.resolve("sum"); 
        //qDebug()<<"MyDLL open:"<<fun1;
        if(fun1)
        {
            qDebug()<<"resolve DLL OK";
            int ret = fun1(26,500);
            qDebug()<<"resolve MyDLL add:"<<ret;
        }else{
            qDebug()<<"resolve MyDLL 失败";
        }
    }else{
         qDebug()<<"加载DLL 失败";
    }
    //MyDll test-----------------------end
 
 
 

猜你喜欢

转载自www.cnblogs.com/darkdance/p/10208156.html