gpt4 book ai didi

c++ - 在 PostgreSQL 中使用 C++ 函数

转载 作者:行者123 更新时间:2023-11-29 12:41:16 24 4
gpt4 key购买 nike

我正在尝试此博客中关于 C++14 and postgres 的代码测试著名问题Writing PostgreSQL Functions in C++的可行性(使用 PostgreSQL 10.1、Ubuntu 16.04)。

代码(extension.cpp)看起来很简单:

extern "C" {
#include <postgres.h> //all C headers and macros go inside extern "C"
#include <utils/rel.h>
PG_MODULE_MAGIC;
}

#include<vector> //C++ headers go outside

extern "C" {
int sumofall() { //wrap the C++ function inside the extern "C" block
auto sum_of_all = 0;
std::vector<int> arr {1,2,3,4,5,6,7};
for (auto& i : arr)
sum_of_all += i;
return sum_of_all;
}
}

代码可以编译,但问题是无法使用以下命令从 PostgreSQL 找到或调用 C++ 函数:

g++ -c -fPIC -Wall -Werror -g3 -O0 -I$(pg_config --includedir-server) extension.cpp
g++ -shared -o my-extension.so extension.o

sudo cp my-extension.so $(pg_config --pkglibdir)

psql -U postgres -h localhost $(whoami) -c "
CREATE OR REPLACE FUNCTION
sumofall() RETURNS integer AS 'my-extension'
LANGUAGE C STRICT;"

Postgres 返回一个错误:

ERROR: could not find function information for function "sumofall"HINT: SQL-callable functions need an accompanyingPG_FUNCTION_INFO_V1(funcname).

我该如何解决这个问题?

最佳答案

阅读the documentation :

The version-1 calling convention relies on macros to suppress most of the complexity of passing arguments and results. The C declaration of a version-1 function is always:

Datum funcname(PG_FUNCTION_ARGS)

In addition, the macro call:

PG_FUNCTION_INFO_V1(funcname);

must appear in the same source file. (Conventionally, it's written just before the function itself.)

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com