OSError: Access Violation Writing with ctypes in python and CreateFileA in c++

  c++, python, serial-port, windows

I have written a program in c++ to communicate with a device connected through the serial port, and I want to integrate that with a larger python file. After debugging for a bit I made this smaller example that gives the same error. My research shows it might have something to do with ctypes and how c++ handles pointers when used in a python file, but I’m not really sure what is even causing this error.


from ctypes import cdll
lib = cdll.LoadLibrary('./serialcpp.so')

class SerialPy(object):
    def __init__(self):
        self.obj = lib.SerialCPP_New()

    def startComm(self):

serialObj = SerialPy()


#include <windows.h>
#include <string>

class SerialCPP {
        HANDLE serialHandle;

        void startComm() {
           COMMTIMEOUTS timeout = { 0 };
           DCB serialParams = { 0 };
           int returnStatus;

           // Start connection to the port
           serialHandle = CreateFileA((LPCSTR) "\.COM3", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);

extern "C" {
    SerialCPP* SerialCPP_New(){ return new SerialCPP(); }
    void SerialCPP_startComm(SerialCPP* SerialCPPObj) { SerialCPPObj->startComm(); }

This is how I compiled the .cpp file into the .so file

>g++ -c -fPIC serialcpp.cpp -o serialcpp.o
>g++ -shared -o serialcpp.so serialcpp.o

When I run the python file after making the .so file, I get this error:

PS C:UsersLukeDocumentsGitHub---------srcmain> & C:/ProgramData/Anaconda3/python.exe c:/Users/Luke/Documents/GitHub/---------/src/main/serialpy.py
Traceback (most recent call last):
  File "c:/Users/Luke/Documents/GitHub/---------/src/main/serialpy.py", line 12, in <module>
  File "c:/Users/Luke/Documents/GitHub/---------/src/main/serialpy.py", line 9, in startComm
OSError: exception: access violation writing 0x00000000B77919B0

I’m using python 3.8.8

When I run this code with the CreateFileA line commented out, it works fine, but I’m not sure what is causing this error. My best guess is it has something to do with the string ".COM3" being written to memory that the python program doesn’t have access too???

Source: Windows Questions