0

我能够在 C/C++ 中编写一个 void 函数,并使用 SWIG 包装到 Python/Numpy (int* INPLACE_ARRAY1, int DIM1),它接收一个int* vector作为参数,对此向量进行一些数学运算,并覆盖同一向量上的结果,并且该结果在内部可用Python 的对象。如下:

    extern "C" void soma_aloc(int* vetor, int tamanho)
    {
       int m = 0;
       int* ponteiro = new int[tamanho];

       for(m = 0; m < tamanho; m++)
       {           
          ponteiro[m] = vetor[m];
       };

       for(m = 0; m < tamanho; m++)
       {
          ponteiro[m] = ponteiro[m] * 10;
       };

       for(m = 0; m < tamanho; m++)
       {
          vetor[m] = ponteiro[m];
       };

       delete [] ponteiro; 
       };

typemaps (DATA_TYPE* INPLACE_ARRAY1, int DIM1)这是一项测试,旨在学习如何使用 SWIG 使用and包装指向 int 和 double 数组的指针(DATA_TYPE* INPLACE_ARRAY2, int DIM1, int DIM2),并且运行良好。

但问题是,我用 char/string Numpy 向量尝试了同样的想法(比如向量vec1 = numpy.array(['a','a','a'])numpy.array(['a','a','a'],dtype=str),并将每个位置更改为 like (['b','b','b']),但 Python 显示in method 'vector_char2D', argument 1 of type 'char *'。可以对 char/string 做同样的事情吗?

    .cpp:

    extern "C" void vetor_char2D(char* vetorchar, int tamanho_vetor)
    {
       for(int i = 0; i < tamanho_vetor; i++)
       {
           vetorchar[i] = 'b';
       };
    };

    .i:

    %module testestring

    %include stl.i
    %include std_string.i

    %{

  #include <stdio.h>
  #include <stdlib.h>
  //#include <string.h>
  #include <string>
  #include <iostream>

  #define SWIG_FILE_WITH_INIT
      #include "testestring.hpp"

    %}

    %include "numpy.i"

    %init %{
     import_array();
    %}

    %apply (char* INPLACE_ARRAY1, int DIM1) {(char* vetorchar, int tamanho_vetor)}
    %include "testestring.hpp" (just the header of the above function vetor_char2D)
    %clear (char* vetorchar, int tamanho_vetor);

我对 SWIG 的体验非常轻松。可以使用char*,char**和/或std::string*/std::string**? 提前致谢!

4

1 回答 1

0

Use std::vector:

void vetor_char2D(std::vector<std::string>& vetorchar)
{
   for (int i = 0; i < vetorchar.size(); i++)
       vetorchar[i] = "b";
};

which indicates clearly that the vector can be modified, and strings within it can be modified, and the SWIG typemaps for STL vectors and strings will work nicely. Note the double rather than single quote for string; Python only has strings no chars so it doesn't matter. You can also make it work with char* etc but it is rarely worth the effort, lot easier to use above. If you don't want to change the source, you can include the above as a wrapper in the .i file via an %inline directive.

Note you should not need the extern C qualifier. And you should use the #include <string> not string.h.

于 2013-11-07T03:43:30.587 回答