从 Windows Flutter 桌面应用程序调用 C# 代码

Pra*_*ell 5 c++ com flutter-desktop

我正在尝试在 flutter 桌面应用程序中调用 ac# dll 中的函数,

在我的 C# dll 中,

using System;
using System.Runtime.InteropServices;

namespace MathLibrary
{
    // NOTE: I have set set [assembly: ComVisible(true)] in AssemblyInfo.cs

   [ComVisible(true)]
   [Guid("66DE2FB9-7A3B-4C33-AF26-9AD5EDD4C71F")]
   [InterfaceType(ComInterfaceType.InterfaceIsDual)]
   public interface IMathLibrary
   {
       [DispId(1)]
       string multiply(int a, int b);
    };
    
    [ComVisible(true)]
    [Guid("021E950E-3612-4FAD-9F15-F61632A95BD8")]
    [ClassInterface(ClassInterfaceType.None)]
    [ProgId("MathLibrary.MathCalc")]
    public class MathCalc : IMathLibrary
    {
        public string multiply(int a, int b)
        {
            return "Product is " + (a * b).ToString();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用这个存储库作为基础 flutter 应用程序。

在应用程序中,我使用平台通道在 dart 和 C++ 代码之间进行通信。在 C++ 代码中,我尝试调用 C# 函数(在文件 windows/runner/custom_channel.cpp 中)。经过一番谷歌搜索后,我想出了以下内容

首先,我向 tlb 文件添加了导入(必须向生成的 tlh 文件添加导入才能使 IntelliSense 工作)

#import "bin/MathLibrary.tlb" 
using namespace MathLibrary;
Run Code Online (Sandbox Code Playgroud)

下面的函数应该调用c#函数

CoInitialize(NULL);
MathLibrary::IMathLibraryPtr IcalcPtr;
HRESULT hr = ::CoCreateInstance(__uuidof(MathLibrary::MathCalc), NULL,
          CLSCTX_INPROC_SERVER,
          __uuidof(MathLibrary::IMathLibrary),
          (void**)&IcalcPtr);
           _bstr_t calcVal;
if (FAILED(hr) || IcalcPtr == nullptr) {
     // CoCreateInstance failed
     // THIS CONDITION IS MET
     (*resPointer)->Error("Cannot Create COM Object");
      return;
 }
//IcalcPtr->multiply(a, b, &calcVal);

calcVal = IcalcPtr->multiply(a, b); 

// not sure how to convert bstr to std::string
const char* calcStr((const char*) calcVal.GetBSTR());
c.assign(calcStr);
CoUninitialize();
Run Code Online (Sandbox Code Playgroud)

CoCreateInstance 失败。

由于我没有c++经验,我很困惑,

  • 什么是 IMathLibraryPtr(我没有在 c# 中定义)
  • 智能感知显示 a 和 bIcalcPtr->multiply(a, b)很长,但我认为它会是 int
  • 当我进行发布构建时,我需要包含 tlb 或 dll
  • 什么是 tlh 文件,它是在构建期间生成的,只有当我向该文件添加导入时,我才获得 Intellisense 支持

我想了解一般如何从 c++ 与 c# com 接口交互以及如何使其在我的情况下工作。示例代码和文档链接会很有帮助

Pra*_*ell 1

问题在于 c# dll 的构建方式,而不是从 c++ 调用它的方式。一旦我为 x64 构建了它,我就为“任何 CPU”构建了 dll。