nodejs在Windows下c++插件引用libpq.dll

414 阅读1分钟

nodejs在Windows下c++插件引用libpq.dll


如需转载请标明出处
QQ技术交流群:129518033

### 文章目录* nodejs在Windows下c++插件引用libpq.dll

环境:

OS : windows 7 64bit

nodejs : 10.153

node-gyp : 6.0.0

编译器 :vs2017

Python : 2.7.15
PostgreSQL: 10.0.10

前言
前面的文章(nodejs在Windows下c++插件编译nodejs在Linux下c++插件运行)介绍了如何在nodejs中编写C++的插件,那么cpp编程中不可避免会引用第三方库。本文以PostgresSQL的libpq.dll为例,介绍C++插件addon中如何使用第三方库。

1. 下载postgresql并安装

在安装目录找到include和lib文件夹,这两个文件夹中有libpq-fe.h头文件和libpq.lib。

在这里插入图片描述

2.编写pg函数调用

hello.cc

#include <node.h>
#include <v8.h>

using namespace v8;

#include "include/libpq-fe.h"

void Method(const v8::FunctionCallbackInfo<Value> &args)
{
    Isolate *isolate = Isolate::GetCurrent();
    HandleScope scope(isolate);
    args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world"));
}

void Init(Handle<Object> exports)
{
    Isolate *isolate = Isolate::GetCurrent();
    PGconn *conn;
    conn = PQconnectdb("postgresql://postgres:123456@localhost/history");
    if (PQstatus(conn) == CONNECTION_OK)
        printf("Connection succeeded.\n");
    else
    {
        printf("Connection failed.\n");
    }

    exports->Set(String::NewFromUtf8(isolate, "hello"),
                 FunctionTemplate::New(isolate, Method)->GetFunction());
}

NODE_MODULE(hello, Init)

3.编写binding.gyp

{
    "targets": [
        {
            "target_name": "hello",
            "sources": ["hello.cc"],
            'include_dirs': [
                "/include"
            ],
            'libraries': [
                "/lib/libpq.lib"
            ]
        }
    ]
}

4.编译.node

node-gyp configure
node-gyp build

5.下载PostgreSQL ODBC driver

www.postgresql.org/ftp/odbc/ve…
ftp.postgresql.org/pub/odbc/ve…
安装后将所有dll放到.ndoe目录下。

或者将postgresql安装自带的libpq.dll及依赖放到.ndoe目录下。

6.编写hello.js

hello.js

//hello.js

var addon = require('./build/Release/hello.node');

console.log(addon.hello()); // 'world'

运行hello.js

通过hello.js调用hello.node,hello.node调用libpq.dll。

7.结果


License

License under CC BY-NC-ND 4.0: 署名-非商业使用-禁止演绎


Reference:
1.nodejs.cn/api/addons.…
2.www.jianshu.com/p/8a9f43045…
3.www.npmjs.com/package/nod…
4.github.com/felixrieseb…
5.www.postgresql.org/ftp/odbc/ve…