未应用Swig数组类型映射

时间:2015-06-04 20:28:16

标签: python arrays swig

我有一个非常简单的swig定义文件,直接从文档中提取字谜,以及几乎与文档完全匹配的示例,但我似乎无法让字体图正常工作。 swig代码,c代码和示例输出位于

之下
%include "stdint.i"
%include "cpointer.i"
%include "carrays.i"


%module example
%{

#include "example.c"

%}

#define __attribute__(x)


%typemap(in) float value[ANY] (float temp[$1_dim0]) {
  int i;
  if (!PySequence_Check($input)) {
    PyErr_SetString(PyExc_ValueError,"Expected a sequence");
    return NULL;
  }
  if (PySequence_Length($input) != $1_dim0) {
    PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements");
    return NULL;
  }
  for (i = 0; i < $1_dim0; i++) {
    PyObject *o = PySequence_GetItem($input,i);
    if (PyNumber_Check(o)) {
      temp[i] = (float) PyFloat_AsDouble(o);
    } else {
      PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");      
      return NULL;
    }
  }
  $1 = temp;
}
%typemap(freearg) float value[ANY] {
   if ($1) free($1);
}

%typemap(memberin) float [ANY] {
  int i;
  for (i = 0; i < $1_dim0; i++) {
      $1[i] = $input[i];
  }
}


%typemap(out) float [ANY] {
  int i;
  $result = PyList_New($1_dim0);
  for (i = 0; i < $1_dim0; i++) {
    PyObject *o = PyFloat_FromDouble((double) $1[i]);
    PyList_SetItem($result,i,o);
  }
}

%include "example.c"

example.c

 /* File : example.c */
#include <stdint.h>

typedef struct __attribute__((packed)) {
    uint8_t mode;
    float vals[4]; // optional
} example_struct;

构建并运行

$ swig -python -Wall example.i
$ make
swig -python example.i
cc -c `python-config --cflags` example.c example_wrap.c
cc -bundle `python-config --ldflags` example.o example_wrap.o -o _example.so
rdeaton@Roberts-Air ~/Projects/air/swigtest (rdeaton_adacs_control●)$ python
Python 2.7.9 (default, Apr  7 2015, 07:58:25)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> s = example.example_struct()
>>> s.vals
[0.0, 0.0, 0.0, 0.0]
>>> s.vals = [1.0]*4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "example.py", line 95, in <lambda>
    __setattr__ = lambda self, name, value: _swig_setattr(self, example_struct, name, value)
  File "example.py", line 59, in _swig_setattr
    return _swig_setattr_nondynamic(self, class_type, name, value, 0)
  File "example.py", line 48, in _swig_setattr_nondynamic
    return method(self, value)
TypeError: in method 'example_struct_vals_set', argument 2 of type 'float [4]'
>>>

0 个答案:

没有答案