Skip to content

Instantly share code, notes, and snippets.

@kostix
Last active October 29, 2022 10:40
Show Gist options
  • Save kostix/28cc4f7bff7a7e56c7b2b4e507ca7ebf to your computer and use it in GitHub Desktop.
Save kostix/28cc4f7bff7a7e56c7b2b4e507ca7ebf to your computer and use it in GitHub Desktop.
Writing C string to a C-allocated buffer from Go
# Project tree:
$ tree
.
├── go
│   ├── go.mod
│   └── strcpy.go
└── run.c
# Build DLL from Go code:
$ cd go
go$ CGO_ENABLED=1 CC=/usr/bin/i686-w64-mingw32-gcc GOOS=windows GOARCH=386 go build -buildmode=c-shared -o ../strcpy.dll
# Return back and build the executable which loads the DLL:
go$ cd ..
$ /usr/bin/i686-w64-mingw32-gcc -o run run.c -L`pwd` -lstrcpy
# Analyze the result:
$ file run.exe
run.exe: PE32 executable (console) Intel 80386, for MS Windows
# Run the resulting executable:
$ wine run.exe
2022/09/09 16:32:07 Test func exec start ...
2022/09/09 16:32:07 Test func exec end ...
test_driver_success
CC = /usr/bin/i686-w64-mingw32-gcc
GOOS = windows
GOARCH = 386
CGO_ENABLED = 1
export CC GOOS GOARCH CGO_ENABLED
.PHONY: all build run clean
all: run
build: run.exe
clean:
@rm run.exe
@rm strcpy.dll
run: run.exe
wine run.exe
strcpy.dll: go/strcpy.go
cd $(CURDIR)/go && \
go build -buildmode=c-shared -o ../strcpy.dll
run.exe: run.c strcpy.dll
$(CC) -o $@ run.c -L$(CURDIR) -lstrcpy
#include <stdlib.h>
#include <stdio.h>
extern void Test(char* params, int count, char* result);
int main(void)
{
char *p;
p = malloc(1000);
if (p == NULL) {
fputs("malloc failed\n", stderr);
return 2;
}
Test(NULL, 1, p);
puts(p);
free(p);
}
package main
// #include <string.h>
// #cgo windows LDFLAGS: -static-libgcc -static
import "C"
import "log"
//export Test
func Test(ptrParams *C.char, count C.int, resultStr *C.char) int {
log.Println("Test func exec start ...")
str := "test_driver_success"
C.strcpy(resultStr, C.CString(str))
log.Println("Test func exec end ...")
return 0
}
func main() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment