为 Python 构建共享库C++时出现分段错误



当我为 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;

最新更新