Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Beazley D.M.SWIG users manual.pdf
Скачиваний:
13
Добавлен:
23.08.2013
Размер:
1.53 Mб
Скачать

SWIG Users Guide SWIG and Python 202

 

Function return typemaps

 

 

char *

%typemap(python,out) char * {

 

$target = PyBuild_Value(“s”,$source);

 

}

 

 

FILE *

%typemap(python,out) FILE * {

 

$target = PyFile_FromFile($source);

 

}

 

 

Pointer handling

SWIG pointers are mapped into Python strings containing the hexadecimal value and type. The following functions can be used to create and read pointer values .

SWIG Pointer Conversion Functions

void SWIG_MakePtr(char *str, void *ptr,

Makes a pointer string and saves it

char *type)

in str, which must be large enough

 

to hold the result. ptr contains the

 

pointer value and type is the string

 

representation of the type.

 

 

char *SWIG_GetPtr(char *str, void **ptr,

Attempts to read a pointer from the

char *type)

string str. ptr is the address of the

 

pointer to be created and type is the

 

expected type. If type is NULL,

 

then any pointer value will be

 

accepted. On success, this function

 

returns NULL. On failure, it returns

 

the pointer to the invalid portion of

 

the pointer string.

 

 

These functions can be used in typemaps. For example, the following typemap makes an argument of “char *buffer” accept a pointer instead of a NULL-terminated ASCII string.

%typemap(python,in) char *buffer { PyObject *o;

char *str;

if (!PyString_Check(o)) { PyErr_SetString(PyExc_TypeError,”not a string”); return NULL;

}

str = PyString_AsString(o);

if (SWIG_GetPtr(str, (void **) &$target, “$mangle”)) { PyErr_SetString(PyExc_TypeError,”not a pointer”); return NULL;

}

}

Note that the $mangle variable generates the type string associated with the datatype used in the typemap.

Version 1.1, June 24, 1997