初始化c ++对象时Cython崩溃

时间:2016-05-24 15:29:56

标签: c++ cython

这是我第一次使用Cython,而且我很难弄清楚出了什么问题。

我有一个C ++类,它接受一些文件名作为字符串,从文件中读取一堆参数,并执行一些繁重的计算。我已经在C ++中对它进行了广泛的测试,但我想在Python中使用它。我从here做了一个例子,编辑它以适应我的课程,并提出以下内容:

# distutils: language = c++
# distutils: sources = linterp1d.cpp
import cython
import numpy as np
cimport numpy as np
from libcpp.string cimport string

cdef extern from "<vector>" namespace "std":
    cdef cppclass vector[T]:
        cppclass iterator:
            T operator*()
            iterator operator++()
            bint operator==(iterator)
            bint operator!=(iterator)
        vector()
        void push_back(T&)
        T& operator[](int)
        T& at(int)
        iterator begin()
        iterator end()


cdef extern from "parameterizedeos.h":
    cdef cppclass parameterizedEOS:
        parameterizedEOS(vector[string],vector[double])
        double pressure(double, double)
        double Cv(double, double)
        double Cp(double, double)
        double entropy(double, double)
        double enthalpy(double, double)
        double getDensityFromPressure(double, double)

cdef class parameterized_EOS:
    cdef parameterizedEOS *thisptr
    # Automatically converts NumPy arrays to STL vectors
    def __init__(self,vector[string] filenames,vector[double] parameters):
        self.thisptr = new parameterizedEOS(filenames, parameters)

    def __dealloc__(self):
        del self.thisptr

    def pressure(self,double rho, double T):
        return self.thisptr.pressure(rho, T)

    def enthalpy(self,double p, double T):
        return self.thisptr.enthalpy(p, T)

    def entropy(self,double p, double T):
        return self.thisptr.entropy(p, T)

    def Cv(self,double p, double T):
        return self.thisptr.Cv(p, T)

    def Cp(self,double p, double T):
        return self.thisptr.Cp(p, T)

    def getDensityFromPressure(self,double p, double T):
        return self.thisptr.getDensityFromPressure(p, T)

(对于任何好奇的人来说,这个课程都是this equation的实现。)

这是我用来测试它的代码:

import numpy as np
import cython
cimport numpy as np
from libcpp.string cimport string
from parameterizedeos import parameterized_EOS


def __main__():
    cdef string str1 = "D:\\Loop Models\\Sodium\\co2_helmholtz_idealgas_coeffs.csv"
    cdef string str2 = "D:\\Loop Models\\Sodium\\co2_helmholtz_real_coeffs_1.csv"
    cdef string str3 = "D:\\Loop Models\\Sodium\\co2_helmholtz_real_coeffs_2.csv"
    cdef string str4 = "D:\\Loop Models\\Sodium\\co2_helmholtz_real_coeffs_3.csv"
    cdef string str5 = "D:\\Loop Models\\Sodium\\co2_helmholtz_real_coeffs_4.csv"

    co2_coeffs = np.array([str1, str2, str3, str4, str5])
    co2_params = np.array([304.128, 467.6, 0.1889241e3])
    co2_eos = parameterized_EOS(co2_coeffs, co2_params)
    print(co2_eos.enthalpy(3e6, 700))

if __name__ == "__main__":
    __main__()

以上将编译,但是当我运行它时,Python崩溃而没有解释为什么。我猜测numpy数组没有正确转换为std::vector<std::string>,这确实会导致C ++类的构造函数抛出错误。所以我有两个问题:如何判断这是否真的是问题,如果是,我该如何解决?

0 个答案:

没有答案