为Python构建共享库C++时的分割错误

2024-03-28 15:38:49 发布

您现在位置:Python中文网/ 问答频道 /正文

在为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;
}

泰斯特·h

#include <string>

class Tesst {
public:
    Tesst();
    Tesst(const std::wstring& t);

};

Tesst.cpp

Tesst::Tesst(const std::wstring& t) {
    wchar_t a = t[0];
}

Tesst::Tesst() {

}

此代码使python应用程序崩溃,并出现分段错误(核心转储)。调试时,可以查看是否删除此语句

wchar_t a = t[0];

一切都完成了。代码起作用。 我有一个问题,为什么这句话会导致崩溃(核心转储)

多谢各位


Tags: thepath核心includesyslibrarypinctypes
1条回答
网友
1楼 · 发布于 2024-03-28 15:38:49
extern "C"
{
// A function doing nothing ;)
int getPrediction(const std::wstring &preword, int dictType);
}

是的,这是行不通的。简单地说,当你想导出C++代码时,接口需要是C兼容的。p>

您可以操作所需的只读数据

# c export
int getPrediction(const char* preword, int dictType);

然后,需要将字节数组转换为正确的格式

    如果你需要C++中的UTF8,只使用^ {CD1> }
  • 如果您需要utf16,use the ugly converterstd::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> utf16conv;

相关问题 更多 >