将 SWIG 包装的 C++ .dll 集成到 C# 项目

问题描述

我在 VS2019 下有 2 个解决方案:RLibrary(包含 C++ 项目)和 VTApp(包含 C# 项目)。

解决方RLibrary 有两个项目:RLib C++ .dll 和 SwigW(包装项目)。 SwigW 生成了以下文件RLibCSHARP_wrap.cxxRLib.csRLib.iRLibPINVOKE .cs.

RLibPINVOKE.cs 中,我有如下几行:

   class RLibPINVOKE {
    //...
     static RLibPINVOKE() {
    }
          [global::System.Runtime.InteropServices.DllImport("SwigW",EntryPoint="CSharp_new_Create")]
          public static extern global::system.intPtr new_Create();
          [global::System.Runtime.InteropServices.DllImport("SwigW",EntryPoint="CSharp_new_Request")]
          public static extern global::system.intPtr new_Request();
          // ...
    }

因此,在构建 RLibrary 解决方案后,我将拥有两个 .dll(也为 .lib)文件RLib.dllSwigW.dll . 我想使用 VTApp 中的 new_Create()new_Request() 函数VTApp 也有两个项目:UICoreUI 引用了 Core。我通过右键单击->添加->现有项目RLibPINVOKE.cs文件添加Core项目中,并尝试使用上述函数命名空间 UI 中的 UI 项目,即,

using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
using Core;
using Newtonsoft.Json;

namespace UI {

public partial class MainWindow {

private void Execute_Req(object sender,EREventArgs e)
{
   //...
   IntPtr p = new_Create();
}

}
}

不幸的是,我收到 CS01013:当前上下文中不存在名称“new_Create”。 错误。 在我看来,即使没有将 SwigW.dll 添加Core 项目中,我也不应该出现这种编译时错误。那么,这里有什么问题呢?如果需要添加 SwigW.dllCore 项目,如何正确添加它?另外,我是否也应该将 RLib.dll 添加Core 中?

解决方法

试试RLibPINVOKE.new_Create()。该方法位于 class RLibPINVOKE

class RLibPINVOKE {
//...

您可能需要一个 using,但 Visual Studio 应该能够在 RLibPINVOKE 上向您推荐它。