【问题标题】:Memory Core Dump C++内存核心转储 C++
【发布时间】:2019-07-28 21:09:36
【问题描述】:

现在,我已将 python 调用到 C++。使用 ctype 在它们之间进行连接。我在运行时遇到了核心转储问题。

我有一个名为“libfst.so”的库 这是我的代码。 NGramFST.h

#include <iostream>
class NGramFST{
private:
    static NGramFST* m_Instace;

public:
    NGramFST(){
    }

    static NGramFST* getInstance() {
        if (m_Instace == NULL){
            m_Instace = new NGramFST();
        }
        return m_Instace;
    }

    double getProbabilityOfWord(std::string word, std::string context) {
        std::cout << "reloading..." << std::endl;
        return 1;
    }

};

NGramFST.cpp

#include "NGramFST.h"
NGramFST* NGramFST::m_Instace = NULL;

extern "C" {
    double FST_getProbability(std::string word, std::string context){
        return NGramFST::getInstance()->getProbabilityOfWord(word, context);
    }
}

这是我的python代码。

from ctypes import cdll
lib = cdll.LoadLibrary('./libfst.so')

#-------------------------main code------------------------
class FST(object):
    def __init__(self):
        print 'Initializing'

    def getProbabilityOfWord(self, word, context):
        lib.FST_getProbability(word, context)

fst = FST()
print fst.getProbabilityOfWord(c_wchar_p('jack london'), c_wchar_p('my name is'))

这是错误

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Aborted (core dumped)

我再次查看,但我无法发现我的问题出在哪里。

【问题讨论】:

  • ctypes 不被称为 c++types 是有原因的。它不能神奇地将 Python 字符串转换为 C++ 字符串。它对 C++ 类型一无所知。为您的库使用与 C 兼容的接口,或者使用现代 Python 绑定库(例如 pybind11)创建模块。
  • 我认为创建实例时有问题,与参数类型无关。

标签: python c++ ctype


【解决方案1】:

当我在下面更改 python 代码时它会起作用

string1 = "my string 1"
string2 = "my string 2"

# create byte objects from the strings
b_string1 = string1.encode('utf-8')
b_string2 = string2.encode('utf-8')

print fst.getProbabilityOfWord(b_string1, b_string2)

和c++代码改变参数类型如下

FST_getProbability(const char* word, const char* context)

【讨论】:

    【解决方案2】:

    ctypes 不理解 C++ 类型(它不称为 c++types)。它无法处理std::string。它不会知道您的函数无论如何都需要 std::string 参数。

    为了使用ctypes,您的库需要一个与 C 兼容的接口。 extern "C" 是必要的,但还不够。这些函数需要实际上可以从 C 中调用。

    更好的是,使用现代 C++/Python 绑定库,例如 pybind11

    【讨论】:

    • 之后,我更改了参数的类型并且它起作用了。谢谢朋友。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多