Search code examples
cpython-3.6python-c-api

Wrong checksum calculated after migrating code to C extension for python 3


I am new to python C extension code and migrating old python 2.7 based c extension code to python 3.6 based c extension code using Visual Studio 2015.

Steps in old code -

  • Use METH_OLDARGS while initialising function
  • Use PyArg_Parse(args,"O",&pyData) for parsing input which is a string passed from python 2.7 code and accepted as PyObject in C Code.
  • Convert input data using PyString_AsStringAndSize to unsigned char*
  • Loop unsigned char* variable and calculate checksum

Steps in new migrated code -

  • Use METH_VARARGS while initialising function
  • Use PyArg_ParseTuple(args, "O", &pyData)for parsing input which is in bytes, passed from python 3.6 code and accepted as PyObject in C Code.
  • Convert input data using PyBytes_AsStringAndSize to char*
  • Loop char* variable and calculate checksum

With new code I am getting wrong checksum. Are the new steps in migrated code correct? Is it due to difference in char* and unsigned char* pointer? Can anybody guide how I can calculate correct checksum?


Solution

  • While posting this question, I thought that it might be because of difference in char* and unsigned char* pointers. I just tried implementing that solution by casting char* pointer to unsigned char* pointer. Did this only while calculating checksum and voila! it worked!