c++ - 在 PostgreSQL 函数或过程中使用 C++ 代码

标签 c++ postgresql

我在与 #include <seal/seal.h> 一起使用的 PostgreSQL 的同一台 PC 上有一个已编译的库当编写一些C++代码时。我必须使用这个库来处理 PostgresSQL 数据库中的一些表值。遗憾的是,在同一台 PC 上使用 Postgres 运行单独的客户端来与数据库进行通信并不是一种选择。

是否可以包含并使用 #include <seal/seal.h> 提供的功能在 PostgreSQL 函数或过程中? 我读到了一些关于使用的内容:

external "C" {

#include <seal/seal.h>
// do something with the seal functions here

}

但是例子不多,我不太明白。 PostgreSQL 文档中有关 C++ 的部分也没有说得更清楚。

最佳答案

正如文档所建议的,从 PostgreSQL 调用的函数必须声明为 extern C,以便 C 代码可以与它们链接。

在必须从 C++ 库调用函数的地方,您可以使用异常处理程序,该异常处理程序使用 catch (...) 来捕获所有可能的异常并通过调用 ereport() 将它们转换为 PostgreSQL 错误消息(在 catch 子句之外,以便调用堆栈上没有任何 C++ 内容)。

如果您必须调用 PostgreSQL C 函数,请确保调用堆栈不包含任何不 plain old data structures 的值。 :

A PDS type in C++, or Plain Old C++ Object, is defined as either a scalar type or a PDS class. A PDS class has no user-defined copy assignment operator, no user-defined destructor, and no non-static data members that are not themselves PDS. Moreover, a PDS class must be an aggregate, meaning it has no user-declared constructors, no private nor protected non-static data, no virtual base classes and no virtual functions.

简而言之,除了调用库函数的地方之外,尽可能使用 C 语言编写代码。

关于c++ - 在 PostgreSQL 函数或过程中使用 C++ 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51600264/

相关文章:

c++ - 改进服务器以处理多个客户端

C++编程题

c++ - cppcheck 警告, "hides typedef with same name"

postgresql - 使用 distinct on 分组时无法正确排序结果

c++ - 在大型 C++ 项目中搜索基类的整个派生类列表

c++ - 使用 C++ 运行批处理

sql - hibernate 4 和 Postgres : How to create a sequence per table?

c# - 什么字符代表 postgresql 中的新行?

sql - 遍历表中的组

java - 将 Spring boot JPA(MySQL) 迁移到 JPA(PostgreSQL) 会引发错误