0

I have this struct in C:

typedef struct THTensor {
  ...
  ptrdiff_t storageOffset;
  ...
} THTensor;

However, the SWIG-generated Java code is:

public SWIGTYPE_p_ptrdiff_t getStorageOffset() {
    return new SWIGTYPE_p_ptrdiff_t(THJNI.THFloatTensor_storageOffset_get(this.swigCPtr, this), true);
}

I'd like that ptrdiff_t is converted to long in Java, not this SWIGTYPE_p_ptrdiff_t, in which I cannot access the actual long value.

How can I control this in SWIG?

Tongfei Chen
  • 613
  • 4
  • 14

1 Answers1

1

There are several options... But ptrdiff_t is unknown to SWIG and to define it just as long is not the best idea.
I would do the following: add %include <stdint.i> to the interface file and then either add in the interface file:

%define ptrdiff_t
intptr_t
%enddef

or add in the source code:

#ifdef SWIG
  %define ptrdiff_t
  intptr_t
  %enddef
#endif // SWIG
...
typedef struct THTensor {
  ...
  ptrdiff_t storageOffset;
  ...
} THTensor;

In such way, the code being wrapped in the interface should have appropriate interpretation of ptrdiff_t, not just an opaque pointer.

luart
  • 1,383
  • 1
  • 18
  • 25
  • My `ptrdiff_t` is mapped to `int` in Java but I'd like to have `long` (64 bit). Do you know how to achieve this? – Tongfei Chen Mar 28 '18 at 16:17
  • `ptrdiff_t` (`intptr_t`) is mapped to Java `int` on x86 and to Java `long` on x64. You should not hardcode `ptrdiff_t` to Java `long` because if such code is compiled on x86 machine then either a compilation error or just the silent truncation of `long` on the pointer initialization will occur (the implicit error is even worse). – luart Mar 29 '18 at 20:00
  • The problem is I'm running on a x64 computer and SWIG generates Java `int` for `intptr_t`. Interestingly, C types `int`, `long` and `long long` are all correctly mapped to Java `int`, `int` and `long`. – Tongfei Chen Mar 31 '18 at 00:32
  • @tongfei-chen, probably you have some issues in the swig environment or compiler settings. You can build x86 binaries on x64 platform [deliberately] if specify respective compiler options. Also, you should check whether x64 or x86 swig build is used. In the end, the issue of mapping `intptr_t` to Java `int` relates to YOUR build environment and/or compiler settings, not to the swig or the listed above header file. – luart Mar 31 '18 at 23:04