How to Define Python Object Members in C Code

Xiao Ling
2 min readAug 19, 2019

--

Three years ago, I created a Python extension module for Dynamsoft Barcode Reader C/C++ SDK. The code skeleton has never been changed until recently the SDK updated to v7.0. In the latest barcode SDK, besides the values of barcode symbologies, there are more constant variables needed to be predefined. The original Python barcode extension is initialized only with some methods, and now I have to add some object members. The article shares the code I’ve refactored in order to add Python object members.

PyTypeObject with Python Object Members

To create a Python module in C, we can use Py_InitModule() function which accepts ‘methods’ argument like this:

Py_InitModule

PyObject* Py_InitModule(char *name, PyMethodDef *methods)Return value: Borrowed reference.Create a new module object based on a name and table of functions, returning the new module object.

Once the module is initialized, we can add objects to the module:

PyModule_AddObject

int PyModule_AddObject(PyObject *module, const char *name, PyObject *value)Add an object to module as name. This is a convenience function which can be used from the module’s initialization function. This steals a reference to value. Return -1 on error, 0 on success.

The DynamsoftBarcodeReaderType is a PyTypeObject which is also a PyObject:

The PyTypeObject structure contains tp_methods (dbr_methods) and tp_members (dbr_methods). Change the code for module initialization:

static PyMethodDef module_methods[] ={{NULL}};PyObject *module = Py_InitModule("dbr", module_methods);

Define a data structure named DynamsoftBarcodeReader:

The DynamsoftBarcodeReader structure contains some PyObjects and the reference of Dynamsoft Barcode Reader.

Define the Python object members:

Initialize the object members in DynamsoftBarcodeReader_new() function and deallocate the object members in DynamsoftBarcodeReader_dealloc() function.

Build the Python module:

python setup.py build install

Use the Python barcode module in Python project:

from dbr import DynamsoftBarcodeReaderdbr = DynamsoftBarcodeReader()# dbr.setFurtherModes(dbr.GRAY_SCALE_TRANSFORMATION_MODE, [dbr.GTM_INVERTED, dbr.GTM_ORIGINAL])

References

Source Code

https://github.com/dynamsoft-dbr/python

Originally published at https://www.codepool.biz on August 19, 2019.

--

--

Xiao Ling
Xiao Ling

Written by Xiao Ling

Manager of Dynamsoft Open Source Projects | Tech Lover

No responses yet