使用 cython 转换采用 std::vector 并输出 std::vector 的现有 C++ 函数

问题描述 投票:0回答:0

我有一个需要 std::vector 并输出 std::vector 的 C++ 文件,如何在 cython 中转换它?

C++ 文件:cpp_func.cpp

std::vector<std::vector<float>> my_cpp_function ( const size_t& p_num                                                    
                                                , const std::vector<float>& x
                                                , const std::vector<std::vector<float>>& table)
{
// Do some heavy calculation & and return a 2D vector called H
    return H;
}

Cython 文件:cython_v1.pyx

import numpy as np
cimport numpy as np
import cython
from libcpp.vector cimport vector

cdef extern from "cpp_func.h":
    vector[ vector[float] ] my_cpp_function ( size_t &p_num                                                                                 
                                            , vector[float] &x                                                     
                                            , vector[ vector[float] ] &table)
   
@cython.boundscheck(False)      
@cython.wraparound (False)      
cpdef float [:,::1] my_cython_func ( size_t p_num, float [:] x, float [:,:] table ):    
    # I have no clue here but basically what is wanted is to use
    # the above imported function to do stuff and output as memory slice
    H = my_cpp_function (p_num, x, table ) 
    return H

在我的Python文件中

import numpy as np
from cython_v1 import my_cython_func

# somewhere here, build the x and table and p_num

H = np.asarray(  my_cython_func(p_num, x, table) )

# H can be used in subsequent cheaper calculation all in python

问题

  1. 我不知道 x 和 table 是在 numpy 中创建的,是否可以被 cython 内的 cpp 函数使用
  2. 我不知道如何将cpp函数中的2D向量转换为内存切片
  3. 如果所有这些都可以快速完成并且不涉及从 cpp 矢量复制到 numpy/memory_slice,那就太好了。

请帮忙。谢谢你。

c++ cython stdvector
© www.soinside.com 2019 - 2024. All rights reserved.