pdemarest
pdemarest

Reputation: 1830

How do I define a SWIG typemap for a reference to pointer?

I have a Publisher class written in C++ with the following two methods:

PublishField(char* name, double* address);
GetFieldReference(char* name, double*& address);

Python bindings for this class are being generated using SWIG. In my swig .i file I have the following:

 %pointer_class(double*, ptrDouble);

This lets me publish a field that is defined in a Python variable:

value = ptrDouble()
value.assign(10.0)
PublishField("value", value.cast())

Trying to using the GetFieldReference method results in a TypeError however:

GetFieldReference("value", newValue)

I think I need to create a typemap for the double*& that returns a ptrDouble, but I am not quite sure what that would look like.

Upvotes: 2

Views: 3033

Answers (2)

Siddu
Siddu

Reputation: 136

This typemap should solve the problem -

// Typemaps for double *&
%typemap(in) double *& (double *ppDouble  = NULL) %{
$1 = &ppDouble  ;
%}

%typemap(argout) double *& {
*(double **)&jarg2 = *$1;
}

%typemap(javain) double *& "$javainput"

You may need to check if assigning jarg2 (in 'argout' typemap) with required double value is correct or jarg1 should be assigned rather.

Upvotes: 0

pdemarest
pdemarest

Reputation: 1830

Here is a working solution that I came up with.

Add a wrapper function to the swig.i file:

%inline %{
    double * GetReference(char* name, Publisher* publisher)
    {
         double* ptr = new double;
         publisher->GetFieldReference(name, ptr);
         return ptr;
    }
%}

Now from Python I can use the following:

value = ptrDouble.frompointer(GetFieldReference("value", publisher)

Upvotes: 1

Related Questions