Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธี Raise Python Exception จาก C Extension

ต้องสร้าง C extension module พร้อม setup.py

setup.py

from distutils.core import setup, Extension
setup(name='helloworld', version='1.0',
      ext_modules=[Extension('helloworld', ['hello.c'])])

Build: $ python setup.py install

Test ใน Python

# test.py
import helloworld

try:
    print(helloworld.helloworld())
except Exception as e:
    print(str(e))

ผลลัพธ์

bad format char passed to Py_BuildValue

C code ใช้ PyErr_SetString() raise exception