【发布时间】: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)创建模块。
-
我认为创建实例时有问题,与参数类型无关。