#221 Java "swigCPtr" is hardcoded and cannot be overriden

Art Clarke

First off, Swig rocks... this is merely a suggestion to make it hopefully rock a little more in Java.

In Swig (as of 1.3.37) the string "swigCPtr" is assumed as the name of the variable that holds the native pointer to the C Object, and this string is inserted directly in the Java proxy class when calls are made requiring a "this" pointer.

This works great, but swig also auto-generates a delete() method that will set swigCPtr to 0, and auto-generates C++ method calls that essentially do (swigCPtr)->func(). If someone has called delete() in the Java wrapper, and then a class (non static) method, they'll get a core-dump as opposed to a more friendly error message.

That said, it would be inappropriate to assume that everyone wants to do something more intelligent (and consequently less efficient) that always assume swigCPtr is valid, so I propose the following change:

Allow people to override the string used to find the current native pointer from the JNI proxy class, but default to "swigCPtr".

For example:

%pragma(java) jniclassthisptrname="mySafeGetCPtr()". That way if no one overrides this "jniclassthisptrname" setting they'll get today's efficient (but potentially unsafe) "swigCPtr". If they do override it, they can intercept deferences of swigCPtr before it causes the core-dump in native code and instead raise an exception.

The attached patch does exactly that for Revision 10894. It should be 100% backwards compatible.


  • Art Clarke

    Art Clarke - 2008-10-27

    Documentation patch for the right way to solve this problem

  • Art Clarke

    Art Clarke - 2008-10-27

    From William Fulton:

    This is the bit of magic you are looking for:

    %typemap(check) SWIGTYPE *self %{
    if (!$1) {
    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "swigCPtr null");
    return $null;

    Explanation: The 'check' typemap is for checking all values arriving in the C/C++ layer. SWIGTYPE is the generic match all type and 'self' is the name of the parameter that the 'this' pointer as marshalled into the C/C++ layer as. The only caveat to be aware of is if you happen to have any parameters that are pointers with the name 'self', the check is also applied to them. Note that this solution will work with all language modules.

  • William Fulton

    William Fulton - 2008-11-01
    • status: open --> closed-rejected
  • William Fulton

    William Fulton - 2008-11-01

    patch not needed due to outlined solution for the problem.


Log in to post a comment.

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:

JavaScript is required for this form.

No, thanks