summaryrefslogtreecommitdiff
path: root/windowsCfileExample.txt
diff options
context:
space:
mode:
Diffstat (limited to 'windowsCfileExample.txt')
-rw-r--r--windowsCfileExample.txt74
1 files changed, 74 insertions, 0 deletions
diff --git a/windowsCfileExample.txt b/windowsCfileExample.txt
new file mode 100644
index 0000000..f4493ad
--- /dev/null
+++ b/windowsCfileExample.txt
@@ -0,0 +1,74 @@
+https://www.reddit.com/r/golang/comments/1ol2tqv/write_postgresql_functions_in_go_golang_example/
+
+
+Write PostgreSQL functions in Go Golang example
+
+It took me a while to figure this out. Go compiles the C files automatically.
+
+add_two.c
+
+#include "postgres.h"
+#include "fmgr.h"
+
+
+PG_MODULE_MAGIC;
+
+
+extern int32 Adder(int32);
+
+
+PG_FUNCTION_INFO_V1(add_two);
+
+
+Datum
+add_two(PG_FUNCTION_ARGS)
+{
+ int32 arg = PG_GETARG_INT32(0);
+ PG_RETURN_INT32(Adder(arg));
+}
+
+adder.go
+
+package main
+
+
+/*
+#cgo CFLAGS: -DWIN32 -ID:/pg18headers -ID:/pg18headers/port/win32
+#cgo LDFLAGS: -LD:/pg18lib
+#include "postgres.h"
+#include "fmgr.h"
+
+
+// Forward declare the C function so cgo compiles add_two.c too.
+extern void init_add_two();
+*/
+import "C"
+
+
+//export Adder
+func Adder(a C.int32) C.int32 {
+ return a + 3
+}
+
+
+func main() {}
+
+Compile it
+
+PS D:\C\myextension> go build -o add_two.dll -buildmode=c-shared
+
+In PostgreSQL: open the query window (adjust path to your generated dynamically loaded library and header file (.dll, .h).
+
+CREATE FUNCTION add_two(int4) RETURNS int4
+
+AS 'D:/C/myextension/add_two.dll', 'add_two'
+
+LANGUAGE C STRICT;
+
+And finally test it:
+
+SELECT add_two(10)
+
+Result:
+ add_two (integer)
+1 13