Search code examples
c#c++postgresqlwinapilibpq

PostgreSQL C++ Api getting error LNK1107: invalid or corrupt file: cannot read at 0x2E8


I try libpqxx and pg_bulkload for C++ data bulk loader from my Simple C# App. Because this two libs on my PC not finally supported. I now , new create simple DLL project,with native PostgreSQL libpq methods.

CPPApp.h

#pragma once  

#ifdef CPPAPP_EXPORTS
#define CPPAPP_API __declspec(dllexport)
#else
#define CPPAPP_API __declspec(dllimport)
#endif  

#include "libpq-fe.h"

extern CPPAPP_API PGconn* conn;

#ifdef __cplusplus
CPPAPP_API extern "C" {
#endif  

    void OpenDb(const char* connStr);

    void CloseDb(void);

    int getVersion(void);

#ifdef __cplusplus
}
#endif

CPPApp.cpp

 #include "stdafx.h"
#include "CPPApp.h" 
#include <iostream> 
using namespace std;

CPPAPP_API PGconn* conn = nullptr;

void OpenDb(const char* connStr)
{
    conn = PQconnectdb(connStr);

    if (PQstatus(conn) != CONNECTION_OK)
    {
        cout << "Connection to database failed." << endl;
        CloseDb();
    }

    cout << "Connection to database - OK" << endl;

}

void CloseDb(void)
{
    PQfinish(conn);
}

int getVersion(void)
{
    int version = PQserverVersion(conn);

    cout << "PostgreSQL version is " << version << endl;

    return version;
}

Error: error LNK1107: invalid or corrupt file: cannot read at 0x2E8

Can I fix this issue?


Solution

  • This error typically happens when you try to link with a DLL (that would be libpq.dll in this case) instead of a library (libpq.lib).

    Assuming you downloaded PostgreSQL for Windows from enterprisedb pre-compiled binaries, there's a lib directory inside the installation directory with libpq.lib. That's the file you want to indicate as an external library to your Visual Studio project.