简体   繁体   中英

Segmentation Fault When Build Shared Library C++ for Python

I faced with a segmentation fault(core dump) when I build shared lib for python. This is Python file

# 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;
}

Tesst.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() {

}

This code makes python app crash with segmentation fault (core dump). When I debug, I can see if I remove this statement

wchar_t a = t[0];

Everything is done. Code works. I have a question, why this statement makes crash (core dump).

Thank you.

extern "C"
{
// A function doing nothing ;)
int getPrediction(const std::wstring &preword, int dictType);
}

Yeah this is not going to work. Simply put, When you want to export C++ code, the interface needs to be C compatible.

You manipulate read-only data you need

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

Then, you need to convert the byte array to the correct format.

  • If you need utf8 in c++ just use std::string s(preword);
  • If you need utf16, use the ugly converter std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> utf16conv;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM