Search code examples
c++winapidllwindows-10-universal

Using a win32 DLL library on a Universal Windows App C++


I was able to compile a dll library based by following the instructions indicated from this tutorial http://tutplusplus.blogspot.com/2011/04/c-tutorial-create-dll-in-vc-20102008.html. I compiled it and there are no problems. I also tested my dll library on an empty win32 console application solution and it compiled fine by adding the header, source file and changing the linker settings. The problem is I can't use the dll library this time on a Universal Windows App solution. I added the header and source files as well as changed the linker settings.

When I compiled the project solution it asked me to include pch.h to the source file of my library so I added the line #include "pch.h" on top.

After that, other compiler errors came up.

'CreateFile': identifier not found and 'SetCommState': identifier not found

I believe the compiler for my current project solution recompiled everything again without considering the dll library's compilation. How can I make the project solution just compile its own source and header files?

Lib Header:

#pragma once
#include <Windows.h>

namespace nmspace
{
    class SerialPort 
    {
    public:
        static __declspec(dllexport) int connect();
    };
}

Lib Source:

#include <iostream>
using namespace std;
#include "SimpleH.h"
#include <Windows.h>

namespace nmspace
{
    int SerialPort::connect() 
    {
        int error = 0;
        DCB dcb;

        memset(&dcb, 0, sizeof(dcb));

        dcb.DCBlength = sizeof(dcb);

        dcb.BaudRate = 57600;
        dcb.Parity = NOPARITY;
        dcb.fParity = 0;
        dcb.StopBits = ONESTOPBIT;
        dcb.ByteSize = 8;

        HANDLE m_serialPortHandle = CreateFile(L"COM7", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, NULL, NULL);

        if (m_serialPortHandle != INVALID_HANDLE_VALUE) {
            if (!SetCommState(m_serialPortHandle, &dcb))
                error = 2;
        }
        else
            error = 1;

        return error;
    }

}

Solution

  • You won't be able to use this DLL because it uses SetCommState function that is only available for desktop applications. You should lookup functions that you are trying to use in a list of desktop APIs available for UWP applications.

    As for CreateFile it is not a function, but a macro expanding to CreateFileA or CreateFileW depending on project Unicode settings. You should use CreateFile2 instead which is available for both Desktop and UWP applications.