2

如何在不使用 libpq++ 或 SQLAPI++ 的情况下在 C++ 和 Postgresql 之间建立接口,因为我尝试安装这两个库但我无法安装(没有 Windows 教程)。我知道 Postgis 和 Pgrouting 使用 C++ .. 也许他们使用另一个库来与 Postgresql 交互......

谢谢 :D

4

1 回答 1

0

有用的文档:

对于要使用 c++ 编码并返回集合的函数 foo,我有以下文件:

  • foo.c
  • foo_driver.h
  • foo_driver.cpp

foo.c

遵循“35.9.9. Returning Sets(返回复合类型的简单 SRF 的完整示例看起来像)”,除了我们调用一个静态函数,该函数将在调用实际 c++ 之前做一些事情(主要是读取更多数据)功能。

  static process ( char* a, bool b, bool c, mystruct* result_tuples, int result_count) {

    <maybe some checking or conversions here of a, b, & c>
    call_cpp_function( a1, b1, c1, result_tuples, result_count )

    }

    PG_FUNCTION_INFO_V1(foo);
    Datum
    foo(PG_FUNCTION_ARGS)    {
      ...
      process(
                pgr_text2char(PG_GETARG_TEXT_P(0)),
                PG_GETARG_BOOL(1),
                PG_GETARG_BOOL(2),
                &result_tuples,
                &result_count);
      ...
      } // end of first call
      ...
      if (call_cntr < max_calls) {
      ...
      else {
        free(result_tuples);
        SRF_RETURN_DONE(funcctx);
      }
    };

foo_driver 具有将在 C 代码和 C++ 代码上使用的 C++ 函数的定义

#ifdef __cplusplus
extern "C" {
#endif

void  call_cpp_function( <parameters > );


#ifdef __cplusplus
}
#endif

foo_driver.cpp

具有函数“call_cpp_function”的实际 cpp 代码,非 postgres 文件将包含在此处,当然您可以在此处包含更多 c++ 文件。具体规则:

  • 不要忘记尝试/捕获,否则您可能会使服务器崩溃
  • 尽快将 C 数组转换为 C++ 容器
  • 不要在 C++ 代码中使用指针,除非
    • 创建结果 C 数组时(请记住我的示例返回一个集合)
  • 最后一次通话结束后不要忘记“免费”声明

例如

#include < vector >
#include < deque >
#include "myclass.h"
void  call_cpp_function( <parameters > ) {
  try {
   <process>
   // use malloc to prepare the C array


  } catch( .. ) {
  // do cleanup
  }
}

注意:此答案未涵盖的内容:编译、链接、添加为扩展。

于 2016-07-26T22:52:30.017 回答