c语言调用python段错误,c-函数调用上的PyObject segfault

作者试图通过Python脚本在C程序中使用Tkinter实现输入获取,但在调用PyObject_CallObject时遇到段错误。文章探讨了可能的原因,如库链接问题,并提供了解决尝试。

我正在尝试使用Python打开对话框以接受输入到我的C应用程序中.

这是我要执行的操作的最小限度表示:

#include

#include

int main()

{

/* Begin Python Ititialization - only needs to be done once. */

PyObject *ip_module_name = NULL;

PyObject *ip_module = NULL;

PyObject *ip_module_contents = NULL;

PyObject *ip_module_getip_func = NULL;

Py_Initialize();

PyEval_InitThreads();

ip_module_name = PyString_FromString( "get_ip" );

ip_module = PyImport_Import( ip_module_name );

ip_module_contents = PyModule_GetDict( ip_module );

ip_module_getip_func = PyDict_GetItemString( ip_module_contents, "get_ip_address" );

/* End Initialization */

PyGILState_STATE state = PyGILState_Ensure();

PyObject *result = PyObject_CallObject( ip_module_getip_func, NULL );

if( result == Py_None )

printf( "None

" );

else

printf( "%s

", PyString_AsString( result ) );

PyGILState_Release( state );

/* This is called when the progam exits. */

Py_Finalize();

}

但是,当我使用PyObject_CallObject调用函数时,应用程序出现段错误.我猜这是因为我正在使用Tk库.我尝试将我的应用程序链接到_tkinter.lib,tk85.lib,tcl85.lib,tkstub85.lib,tclstub85.lib,但这些都无济于事.我很沮丧…

这是脚本:

import Tkinter as tk

from tkSimpleDialog import askstring

from tkMessageBox import showerror

def get_ip_address():

root = tk.Tk()

root.withdraw()

ip = askstring( 'Server Address', 'Enter IP:' )

if ip is None:

return None

ip = ip.strip()

if ip is '':

showerror( 'Error', 'Please enter a valid IP address' )

return get_ip_address()

if len(ip.split(".")) is not 4:

showerror( 'Error', 'Please enter a valid IP address' )

return get_ip_address()

for octlet in ip.split("."):

x = 0

if octlet.isdigit():

x = int(octlet)

else:

showerror( 'Error', 'Please enter a valid IP address' )

return get_ip_address()

if not ( x < 256 and x >= 0 ):

showerror( 'Error', 'Please enter a valid IP address' )

return get_ip_address()

return ip

编辑:添加了我的线程设置

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值