用Cython分段故障处理

用Cython分段故障处理

本文介绍了用Cython分段故障处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我包了一些C库,和我有一个功能,在某些情况下可能会引起分段错误。在这种情况下,我需要调用第二个函数,它将在这种情况下顺利完成。

I am wrapping some C library, and I have one function which in some cases may result with segmentation fault. In that case I need to call second function, which will in that situation complete successfully.

有谁知道我该怎么处理用Cython分割的错吗?

Does anyone knows how can I handle segmentation fault in cython?

推荐答案

一个简单的例子,可能会帮助(使用信号

A short example that might help (using signal):

example.h文件(假设用Cython扩展名为 myext.pyx

example.h (assuming the Cython extension is named myext.pyx)

// Header autogenerated by Cython when declaring "public api" functions
#include "../myext_api.h"

void handleFuncFailure(char *func1_name, char *func2_name);
void generateSegFault();

example.c

example.c

#include <example.h>
#include <signal.h>

static char *func2name;

static void handler2(int sig)
{
    // Catch exceptions
    switch(sig)
    {
        case SIGSEGV:
            fputs("Caught SIGSEGV: segfault !!\n", stderr);
            break;
    }
    int error;
    // "call_a_cy_func()" is provided by "myext.pyx"
    call_a_cy_func(func2name, &error);
    exit(sig);
}

void handleFuncFailure(char *func1_name, char *func2_name) {

    // Provided by autogenerated "myext_api.h" header
    import_myext();

    func2name = func2_name;
    signal(SIGSEGV, handler2);
    int error;
    // "call_a_cy_func()" is provided by "myext.pyx"
    call_a_cy_func(func1_name, &error);
}

void generateSegFault() {
    *(int*) 0 = 0;
}

myext.pyx

myext.pyx

# Helper function to call a function by its name
# "public api" enables to call this function from C side (See above)
cdef public api void call_a_cy_func(char* method, bint *error):
    if (method in globals()):
        error[0] = 0
        globals()[method]();
    else:
        error[0] = 1

# Expose C functions
cdef extern from "src/example.h":
    void handleFuncFailure(char *func1_name, char *func2_name)
    void generateSegFault()

# The unreliable function
def func1():
    print "hello1 ! Generating segfault..."
    generateSegFault()

# The reliable function
def func2():
    print "hello2 ! Running safe code..."

# To be called from the Cython extension inner code
cdef myHandleFuncFailure(f1, f2):
    handleFuncFailure(f1, f2)

# To be called from Python source by importing "myext" module
def myHandleFuncFailure2():
    myHandleFuncFailure("func1", "func2")

输出继电器

Ouput

hello1!生成段错误...

陷入SIGSEGV:段错误!

Caught SIGSEGV: segfault !!

hello2!运行安全code ...

hello2 ! Running safe code...

我希望这给一些想法,至少...

I hope this gives some ideas, at least...

这篇关于用Cython分段故障处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 21:23