2017-10-06 61 views
-1

我在Visual Studio中使用C++进行编程。运行代码在dll中使用时不起作用

这是我的子程序,这给了我一个特定的值从双阵列回:

double specific_value_search(std::string mol_fractions_name[], std::string mass_fractions_name_output[], double mass_fractions_output[], int molecule) 
{ 
    double specific_value=5;                
    std::string a = mol_fractions_name[molecule]; 
    std::string b; 
    for (int i = 0; i <= 11; i++) 
    { 
     b = mass_fractions_name_output[i]; 
     if (a.compare(b) == 0) 
     //if ((a.find(b) != std::string::npos))...this was my second try           // sollte string b in Zeile a gefunden werden, dann... 
     { 
      specific_value = mass_fractions_output[i]; 
      break; 
     } 
    } 
    return specific_value; 
} 

所以当我执行在我的项目这段代码到一个.exe,代码运行正常。 但是当我把它编译成一个DLL,通过一个外部程序的运行它,值返回5,因为我initalisation(不初始化,因为试图返回未初始化的变量程序崩溃。

我增加值从下面

在截图视觉工作室有没有人有什么建议吗?

Screenshot 1 - values from visual studio

Screenshot 2 - values from visual studio

+1

你能否让[mcve]至少显示你如何调用该方法? – user463035818

+0

如果你打算使用'std :: string',为什么不'std :: vector '?你的代码对传递的数组完全没有边界检查,因为没有办法进行边界检查。使用'std :: vector',至少你有'size()','at()'等来做这些事情。 – PaulMcKenzie

+0

你可以在'std :: string'中使用'operator ==',你不需要使用'compare'方法。 –

回答

0

如果你可以使用标准容器(std :: map或std :: unsorted_map),那么这就变得微不足道了。

std::map<std::string, double> fractionNames; 
// fill map 
double specificValue = fractionNames[mol_fractions_name[molecule]]; 

如果它可能是molecule比名的数量较大,或者你需要生成一个错误,如果分数名称未在地图上找到,那么你就必须添加一些代码来检测和处理这些情况。

如果您不能使用地图,那么你可以使用一个矢量

struct FractionName { 
    std::string name; 
    double value; 
} 
typedef std::vector<FractionName> FractionNameVector; 
FractionNameVector fractionNames; 
// again fill fractionNames 

FractionNameVector::iterator iter = std::find(fractionNames.begin(), fractionNames.end(), SearchPredicate(mol_fractions_name[molecule])); 

这将需要这样

struct SearchPredicate 
{ 
    bool operator()(const FractionName& haystack) { return haystack.name == 
     needle; } 
    explicit SearchPredicate(const std::string name) : needle(name) {} 
    std::string needle; 
}; 

一个SearchPredicate,如果你使用的是C你可以使用lambda ++ 11或更高版本。