Search code examples
c#c++-cliswig

Integrate C++ .dll wrapped by SWIG to C# project


I have 2 solutions under VS2019: RLibrary (contains C++ project) and VTApp (contains C# project).

Solution RLibrary has two projects: RLib C++ .dll and SwigW (wrapper project). SwigW generated the following files: RLibCSHARP_wrap.cxx, RLib.cs, RLib.i and RLibPINVOKE.cs.

In the RLibPINVOKE.cs I have lines like:

   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();
          // ...
    }

So, after building RLibrary solution I will have two .dll (also .lib) files: RLib.dll and SwigW.dll. I want to use new_Create(), new_Request() functions from the VTApp. VTApp has two projects as well: UI and Core. UI has a reference to Core. I added RLibPINVOKE.cs file to the Core project by just Right Click->Add->Existing item and tried to use above mentioned functions from the UI project within namespace UI, i.e.,

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();
}

}
}

Unfortunately, I am getting CS01013: The name 'new_Create' does not exist in the current context. error. In my opinion, even without adding SwigW.dll to the Core project I shouldn't have had this kind of compile time error. So, what is the problem here? How can I add SwigW.dll into the Core project properly if I need to add it? Also, should I add RLib.dll to the Core as well?


Solution

  • Try RLibPINVOKE.new_Create(). The method is inside a class RLibPINVOKE

    class RLibPINVOKE {
    //...
    

    You'll perhaps need a using, but the Visual Studio should be able to suggest it to you on the RLibPINVOKE.