swig in c# - HandleRef could not be found in portable class library

1.2k views Asked by At

I'm tring to wrap my c++ code to c# with using Swig. If the output destination of C# files is class library , there is no error and succesfully build.

However I want to support both windows phone 8.1 and windows 8.1 because of this reason I'm using portable class library rather than normal class library. In this situation I'm getting error that says;

The type or namespace name 'HandleRef' does not exist in the namespace 'System.Runtime.InteropServices' (are you missing an assembly reference?)

I really don't know what I am missing. What is the solution of this problem? My guess windows phone 8.1 and windows 8.1 does not support HandleRef but I'm not sure. If it so, What should I do?

1

There are 1 answers

1
Littlefinix On

This question is a bit older, but having had the same problem when using .NET Core I thought I'd share my Solution.


Change the imtype and csbody

To tell SWIG to stop using HandleRef you have to change the %typemap(imtype) and %typemap(csbody) of all default (or of specific) types.

imtype specifies the type that appears in your modulenamePINVOKE method parameters. Change it to something that can be marshaled from/to a pointer type.

csbody replaces the entire body of your SWIGTYPE_ classes, meaning you'll have to implement you own (You have to, to change the variable that is stored as HandleRef). If your new implementation doesn't have a getCPtr method you have to change %typemap(csin) as well

Here is an example that uses System.IntPtr instead of HandleRef, place it at the top in your interface file:

%typemap(imtype) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "System.IntPtr"
%typemap(csin) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "$csinput.Pointer"

%typemap(csbody) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) %{

  private volatile System.IntPtr swigCPtr;

  protected $csclassname() 
  {
    swigCPtr = System.IntPtr.Zero;
  }

  internal System.IntPtr Pointer
  {
    get
    {
      return swigCPtr;
    }
  }
%}

Note: SWIGTYPE is a placeholder for any type.

Reference: SWIG 3.0 Documentation - Chapter 20 "SWIG and C#"