這是我第一次提出關于堆疊溢位的問題,所以請多多
包涵Python.h
起初我使用的是由 python 解釋器直接提供的eval 函式,但是在閱讀了為什么 eval 可能是危險的之后,我按照這里的建議使用了一個名為NumExpr的python 庫,但是當我使用該 python 庫來評估代數運算式時,我得到了第二次輸入運算式時出現分段錯誤(它第一次起作用)
這是示例代碼:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <Python.h>
void my_pause()
{
int c;
printf("\n Press the enter key to continue...");
fflush(stdout);
while ((c = getchar()) != '\n' && c != EOF) {}
}
void main()
{
char selec[8], temp;
while(1)
{
main:
printf("Enter here : ");
scanf("%s" , selec);
scanf("%c" , &temp); //this scanf is necessary as it solves the input buffer
if(strcmp(selec,"math-exp")==0)
{
printf("\n\n Please note the opreators : ");
printf("\n for addition ' '");
printf("\n for subtraction '-'");
printf("\n for multiplication '*'");
printf("\n for division '/'");
printf("\n for exponential power '**'");
printf("\n for percentage '%%'");
printf("\n for knowing about various functions that can be used please check documentation");
//I had to print this using printf and not by python print itself is to solve the EOL error
printf("\n\n Enter the mathematical expression : ");
Py_Initialize();
PyRun_SimpleString("import numexpr as ne");
PyRun_SimpleString("math_exp = input()");
//I had to print this using printf and not by python print itself is to solve the EOL error
printf("\n The answer is : ");
fflush(stdout);
PyRun_SimpleString("print(math_exp)");
Py_Finalize();
my_pause();
system("clear");
goto main;
}
else if(strcmp(selec,"exit")==0)
{
exit(0);
}
}
}
這第一次作業得很好,但如果你第二次輸入'math-exp'來輸入另一個運算式,它將顯示分段錯誤。我正在使用 linux mint、gcc 9.4.0、python 3.8。下面是我用來編譯代碼的命令:
gcc test.c -o test.bin -I"/usr/include/python3.8" -L"/usr/lib/python3.8" -lpython3.8
在此先感謝您的幫助!
uj5u.com熱心網友回復:
Py_Finalize多次呼叫會造成記憶體泄漏。之前移動你的Py_Finalize線exit(0)
這個bug已經在2007年打開了,上個月才關閉。https://bugs.python.org/issue1635741
在 python 3.11 中解決。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/475035.html
標籤:Python C python-3.x 分段故障 python嵌入
上一篇:使用python將messagePack決議為Json
下一篇:通過多個嵌套鍵對資料進行分組
