为 Python 构建共享库C++时出现分段错误
Segmentation Fault When Build Shared Library C++ for Python
当我为 python 构建共享库时,我遇到了分段错误(核心转储(。 这是蟒蛇文件
# coding=utf-8
import sys, platform
import ctypes, ctypes.util
path_libc = "cmake-build-debug/libuntitled.so"
MAIN_DICT = 1
# mylib_path = ctypes.util.find_library(path_libc)
# if not mylib_path:
# print("Unable to find the specified library.")
# sys.exit()
try:
libc = ctypes.CDLL(path_libc)
print(libc.getPrediction("tôi cô đơn", MAIN_DICT))
except OSError:
print("Unable to load the system C library")
sys.exit()
print('Succesfully loaded the system C library from', path_libc)
PNI.h
#ifndef UNTITLED_PIN_H
#define UNTITLED_PIN_H
#include <string>
extern "C"
{
// A function doing nothing ;)
int getPrediction(const std::wstring &preword,
int dictType);
}
#endif //UNTITLED_PIN_H
PNI.cpp
#include "PIN.h"
#include "Tesst.h"
int getPrediction(const std::wstring &preword, int dictType) {
Tesst a(preword);
return 0;
}
泰斯特·
#include <string>
class Tesst {
public:
Tesst();
Tesst(const std::wstring& t);
};
泰斯特.cpp
Tesst::Tesst(const std::wstring& t) {
wchar_t a = t[0];
}
Tesst::Tesst() {
}
此代码使 python 应用程序崩溃并出现分段错误(核心转储(。调试时,我可以查看是否删除了此语句
wchar_t a = t[0];
一切都完成了。代码有效。 我有一个问题,为什么这个陈述会导致崩溃(核心转储(。
谢谢。
extern "C"
{
// A function doing nothing ;)
int getPrediction(const std::wstring &preword, int dictType);
}
是的,这是行不通的。简单地说,当你要导出C++代码时,接口需要与C兼容。
您操作所需的只读数据
# c export
int getPrediction(const char* preword, int dictType);
然后,您需要将字节数组转换为正确的格式。
- 如果你在 c++ 中需要 utf8,只需使用
std::string s(preword);
- 如果您需要utf16,请使用丑陋的转换器
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> utf16conv;
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?