Отображение только функции C ++, которая использует другие классы, используя Swig - PullRequest
0 голосов
/ 07 октября 2018

Я новичок в C ++, но пытаюсь отобразить одну функцию, которая принимает аргумент vector<string> и возвращает тип vector<double>, используя Swig, чтобы я мог использовать ее в Python.Эта функция в данный момент принимает аргументы из командной строки при выполнении моего файла через main (), но она просто передает аргументы функции, к которой я хочу, чтобы Python получил доступ (get_equities()).

Я изо всех сил пытался разобраться с этим, так как большинство примеров имеют дело либо с классами отображения, либо с очень простыми примерами функций (такими как swig tut), и я также не уверен в том, что файл ссылается на другие классы в другихфайлы через включение файла в другом каталоге.

Я следую примеру здесь

Код, содержащий мою функцию: myfile.cpp:

#include "omp/EquityCalculator.h"
#include <iostream>
using namespace omp;
using namespace std;

// Function prototype (declaration)
vector<double> get_equities(vector<string> args);

int main(int argc, char *argv[])
{
    vector<string> args(argv, argv + argc);
    vector<double> equities;
    equities = get_equities(args);
};

vector<double> get_equities(vector<string> args) {

    int argc = args.size();

    string board_string = args[1];

    EquityCalculator eq;
    vector<CardRange> ranges;
    for( int i = 2; i < argc; i++ ) {
        ranges.push_back(args[i]);
    };

    uint64_t board = CardRange::getCardMask(board_string);

    eq.start(ranges, board);
    eq.wait();

    vector<double> result;

    auto r = eq.getResults();
    // 2 to 4; 2 to 3
    //todo: 
    for( int i = 2; i < argc; i++ ) {
        result.push_back(r.equity[i - 2]);
    }
    return result;
}

Мой интерфейсный файл в настоящее время выглядит следующим образом, что я думаю, вероятно, неправильно:

/* example.i */
%module example
#include "EquityCalculator.h" 
%include <std_string.i>
%include <std_vector.i>

%{
    /* Put header files here or function declarations like below */
    extern std::vector<std::double> get_equities(std::vector<std::string>);
%}

extern vector<double> get_equities(vector<string> args);

Я создаю оболочку с swig -c++ -python -o example_wrap.cxx example.i.

Кажется, все в порядке, но затем запустите файл setup.py с python3 setup.py build_ext --inplace для следующего:

#!/usr/bin/env python3

"""
setup.py file for SWIG example
"""

from distutils.core import setup, Extension


example_module = Extension('_example',
                           sources=['example_wrap.cxx', 'my_file.cpp'],
                           )

setup (name = 'example',
       version = '0.1',
       author      = "SWIG Docs",
       description = """Simple swig example from docs""",
       ext_modules = [example_module],
       py_modules = ["example"],
       )

Есть много ошибок, например:

In file included from example.cpp:1:
In file included from ./omp/EquityCalculator.h:4:
In file included from ./omp/CombinedRange.h:4:
In file included from ./omp/HandEvaluator.h:4:
./omp/Util.h:104:37: error: expected '(' for function-style cast or type construction
    if (alignment < OMP_ALIGNOF(void*))
                                ~~~~^
./omp/Util.h:95:36: note: expanded from macro 'OMP_ALIGNOF'
    #define OMP_ALIGNOF(x) alignof(x)
                                   ^
./omp/Util.h:104:21: error: expected expression
    if (alignment < OMP_ALIGNOF(void*))
                    ^
./omp/Util.h:95:37: note: expanded from macro 'OMP_ALIGNOF'
    #define OMP_ALIGNOF(x) alignof(x)
                                    ^
./omp/Util.h:105:37: error: expected '(' for function-style cast or type construction
        alignment = OMP_ALIGNOF(void*);
                                ~~~~^
./omp/Util.h:95:36: note: expanded from macro 'OMP_ALIGNOF'
    #define OMP_ALIGNOF(x) alignof(x)
                                   ^
./omp/Util.h:105:21: error: expected expression
        alignment = OMP_ALIGNOF(void*);

Что я делаю не так?

...