I\'m having trouble with swig and char ** as pointer to a variable char * (not as a list of char *!!!). I couldn\'t find out a way to wrap the pointer to a char *.
T
From the SWIG 3.0 documentation, near the end of §9.2.1 cpointer.i
:
Note: None of these macros can be used to safely work with strings (char * or char **).
So you will have to resort to typemaps. Below is an example:
pointers.cpp
I had to change your source slightly. A char**
argument should return the allocated pointer, and not free it:
#include <string.h>
#include <stdlib.h>
#include "pointers.h"
void conc(char *str1, char *str2, char **res){
*res = (char *)malloc(strlen(str1)+strlen(str2)+1);
strcpy(*res,str1);
strcat(*res,str2);
}
pointers.h
void conc(char *str1, char *str2, char **res);
pointers.i
This version of the swig file declares the typemaps to handle the char**
output argument.
%module pointers
%{
#include "pointers.h"
%}
// This input typemap declares that char** requires no input parameter.
// Instead, the address of a local char* is used to call the function.
%typemap(in,numinputs=0) char** (char* tmp) %{
$1 = &tmp;
%}
// After the function is called, the char** parameter contains a malloc'ed char* pointer.
// Construct a Python Unicode object (I'm using Python 3) and append it to
// any existing return value for the wrapper.
%typemap(argout) char** (PyObject* obj) %{
obj = PyUnicode_FromString(*$1);
$result = SWIG_Python_AppendOutput($result,obj);
%}
// The malloc'ed pointer is no longer needed, so make sure it is freed.
%typemap(freearg) char** %{
free(*$1);
%}
// Now that the typemap exists, let swig wrap the header.
%include "pointers.h"
test.py
import pointers
result = pointers.conc('Hello ','World!');
print(result)
Output
Hello World!