【发布时间】:2017-10-30 16:29:53
【问题描述】:
我在使用 swig 为 python 包装 c++ 时遇到了困难,让我卡住的是 char** 引用的输出参数(char* 列表)。
我的c++是这样的:
class dict{
int getKeys(const char **&keys, int &result_length)
}
我知道我需要使用typemap,我写在swig接口文件(.i)中:
%{
#include "dict.hpp"
%}
%apply int &OUTPUT { int & };
%typemap(in, numinputs=0) char **& (char **temp) {
$1 = &temp;
}
%typemap(argout) char**& %{
int ntokens;
int itoken;
for (ntokens = 0; *$1[ntokens] != NULL; ntokens++) {
}
PyObject* temp = NULL;
temp = $result;
$result = PyList_New(ntokens);
for (itoken = 0; itoken < ntokens; itoken++) {
PyList_Append($result, PyUnicode_FromString( *$1[itoken] ));
}
PyObject* list_temp = NULL;
list_temp = $result;
$result = PyList_New(1);
PyList_SetItem($result, 0, temp);
PyList_Append($result, list_temp);
Py_DECREF(temp);
Py_DECREF(list_temp);
%}
%typemap(freearg) char**& %{
free(*$1);
%}
%include "dict.hpp"
我在编译.i文件时没有问题,但是在python中使用时,python.exe停止工作
resultCode, keys, keysCount = dict.getkeys()
我通过引用 char* 成功地将输出参数包装为:
%typemap(in, numinputs=0) char *& (char *temp) {
$1 = &temp;
}
%typemap(argout) char*& %{
PyObject* temp = NULL;
temp = $result;
$result = PyList_New(1);
PyList_SetItem($result, 0, temp);
PyList_Append($result, PyUnicode_FromString(*$1));
Py_DECREF(temp);
%}
%typemap(freearg) char*& %{
free(*$1);
%}
但是如何通过引用 char**(char* 列表)来包装输出参数?有人可以帮忙吗?
【问题讨论】:
标签: python list reference char swig