關於char*
全局 char* 變量
SWIG 使用malloc() 或者 new 來給新值分配內存。比如如下形式的一個變量:
char *foo ;
SWIG 生成如下代碼:
/* C mode */
void foo_set(char *value) {
if (foo) free(foo);
foo = (char *) malloc(strlen(value)+1);
strcpy(foo,value);
}
/* C++ mode. When -c++ option is used */
void foo_set(char *value) {
if (foo) delete [] foo;
foo = new char[strlen(value)+1];
strcpy(foo,value);
}
如果這不是你希望的行爲,比如這是個只讀變量,可以用 %immutable 標識。或者你可以寫個自己的輔助賦值函數,比如:
%inline %{
void set_foo(char *value) {
strncpy(foo,value, 50);
}
%}
注意:如果你寫了如上形式的函數,你就必須在目標語言裏調用這個函數來賦值(這使得它在目標語言中看上去不像個變量),比如在Python 中你必須這樣寫:
>>> set_foo("Hello World")
Setting const char* variable may leak memory
SWIG 這個警告信息,通常是由C 裏的const char* 變量引起的。SWIG缺省照樣會給該變量生成 setting 和 getting 函數,但是並不是釋放前一次的內容(結果就是可能有內存泄漏)。
一種常犯的錯誤
在C/C++裏常有如下的定義:
char *VERSION = “1.0”;
SWIG缺省生成的代碼(參見上文),SWIG會用free() 或 delete 釋放內存,這將導致保護錯。解決辦法:
將變量標記爲read-only. (%immutable), 寫一個typemap (見Document 第6章),或者寫一個特殊的set function.(如上)。另外也可以把變量定義成字符數組:
char VERSION[64] = "1.0";
爲C struct 添加 member function
假設有如下C頭文件:
/* file : vector.h */
...
typedef struct Vector {
double x,y,z;
} Vector;
可以通過SWIG的 interface 讓 Vector 看上去像個類。// file : vector.i
%module mymodule
%{
#include "vector.h"
%}
%include "vector.h" // Just grab original C header file
%extend Vector { // Attach these functions to struct Vector
Vector(double x, double y, double z) {
Vector *v;
v = (Vector *) malloc(sizeof(Vector));
v->x = x;
v->y = y;
v->z = z;
return v;
}
~Vector() {
free($self);
}
double magnitude() {
return sqrt($self->x*$self->x+$self->y*$self->y+$self->z*$self->z);
}
void print() {
printf("Vector [%g, %g, %g]\n", $self->x,$self->y,$self->z);
}
};
%extend 指令也可以用在struct定義之內:
// file : vector.i
%module mymodule
%{
#include "vector.h"
%}
typedef struct Vector {
double x,y,z;
%extend {
Vector(double x, double y, double z) { ... }
~Vector() { ... }
...
}
} Vector;
%extend 指令也可以直接引用C裏的函數,只要這些函數名按照約定的命名規範:
/* File : vector.c */
/* Vector methods */
#include "vector.h"
Vector *new_Vector(double x, double y, double z) {
Vector *v;
v = (Vector *) malloc(sizeof(Vector));
v->x = x;
v->y = y;
v->z = z;
return v;
}
void delete_Vector(Vector *v) {
free(v);
}
double Vector_magnitude(Vector *v) {
return sqrt(v->x*v->x+v->y*v->y+v->z*v->z);
}
// File : vector.i
// Interface file
%module mymodule
%{
#include "vector.h"
%}
typedef struct Vector {
double x,y,z;
%extend {
Vector(int,int,int); // This calls new_Vector()
~Vector(); // This calls delete_Vector()
double magnitude(); // This will call Vector_magnitude()
...
}
} Vector;