我无法弄清楚如何编组指向python和C之间的c-string的指针。我试图用签名包装现有的库:
int connect(char* url, char** host, char** port, char** path);
connect函数设置主机,端口和路径。网址参数很好,但是双指针引起了麻烦。
我需要在我的.i文件中放置什么才能正确地编组双指针?
答案 0 :(得分:4)
如果char**
参数仅为输出,则以下内容将起作用。由于未指定实现,因此我将malloc
返回的参数并假设为ASCII / UTF-8字符串。我还假设Python 3。
%module x
%{
#include <stdlib.h>
#include <stdio.h>
%}
%include <exception.i>
// This makes char** output-only and it won't be a required parameter in the
// Python interface. A temporary char* is created for each char** encountered
// and its address is used for the char** parameter.
%typemap(in,numinputs=0) char** (char* tmp) %{
$1 = &tmp;
%}
// This typemap is processed after calling the function.
// It converts the returned value to a Python Unicode string.
// The malloc'ed return value is no longer needed so is freed.
%typemap(argout) char** (PyObject* tmp) %{
tmp = PyUnicode_FromString(*$1);
$result = SWIG_Python_AppendOutput($result,tmp);
free(*$1);
%}
%inline %{
int connect(char* url, char** host, char** port, char** path)
{
*host = malloc(10);
*port = malloc(10);
*path = malloc(10);
strcpy(*host,"host");
strcpy(*port,"port");
strcpy(*path,"path");
return 1;
}
%}
演示:
>>> import x
>>> x.connect('url')
[1, 'host', 'port', 'path']