twid
twid

Reputation: 6686

customizing code generated by swig

Is it possible to modify code generated by swig? i want to replace code generated by swig. For example

i have struct

typedef struct Test {
  char *buffer;
} Test;

Swig will create following code

SWIGEXPORT void JNICALL Java_Test_1buffer_1set(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2) {
  struct Test *arg1 = (struct Test *) 0 ;
  char *arg2 = (char *) 0 ;

  (void)jenv;
  (void)jcls;
  (void)jarg1_;
  arg1 = (struct Test*)&jarg1; 
  arg2 = 0;
  {
    if (arg2) {
      arg1->buffer= (char const *) malloc(strlen((const char *)arg2)+1);
      strcpy((char *)arg1->buffer, (const char *)arg2);
    } else {
      arg1->buffer= 0;
    }
  }
  if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2);
}

Is it possible to replace strcpy with other function say customized_strcpy?

Upvotes: 0

Views: 298

Answers (1)

The memberin typemap is responsible for code you've shown. You can replace the strcpy as you want by writing a custom typemap. For example:

%module example

%typemap(memberin) char *buffer {
  // Keep whatever other bits of the mechanics you care about 
  if ($1) free($1);
  if ($input) {
    $1 = malloc(strlen($input)+1);
    customized_strcpy($1, $input);
  } else {
    $1 = 0;
  }
}

%inline %{
typedef struct Test {
  char *buffer;
} Test;
%}

Which generates the code you want.

Upvotes: 2

Related Questions