(Cross posting with SO 
https://stackoverflow.com/questions/61258160/swig-generated-go-wrapper-mishandling-pointers-to-pointers-to-structs
)

Hi folks,

We're integrating a Go program with a 3rd party C api, but are getting some 
odd results when working with pointers to pointers to structs. A model of 
the header file looks a bit like this...

//mytest.h 

typedef struct Books {
 char title[50];
 char author[50];
 char subject[100];
 int book_id;
} 

Book; extern void initbook(Book** b);

With a model implementation like this...

//mytest.c 
#include <stdlib.h> 
#include <string.h> 
#include <stdio.h> 

typedef struct Books {
 char title[50];
 char author[50];
 char subject[100];
 int book_id; 
} Book; 

void initbook(Book** b){ *b = malloc(sizeof(Book));
 strcpy( (*b)->title, "A Book Title"); 
}

We've tried wrapping the API with a very simple SWIG file which looks like 
this...

%module mytest %{
 #include "./mytest.h" 
%} 
%include "./mytest.h"

And call it from a Go main function like this...

//main.go 

package main 
import "fmt" 
import "mytest" 
func main() {
 bookPtr := mytest.NewBook()
 mytest.Initbook(bookPtr)
 fmt.Printf("title: '%s'\n", bookPtr.GetTitle()) 
}

However, we've found when we run this we the value being returned from 
GetTitle() is garbled....

> go run ../main.go 
title: '??'

Digging in to the generated C code we found that editing the Book 
constructor to return Book** rather than Book*, and then modifying the 
GetTitle function to receive a Book** instead of Book* things started 
working as expected.

Any hints on how we might configure SWIG to generate a version of the code 
which works for us. without us having to hack what it generates?

Thanks!

Mark

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/acc6b4f8-2928-4b07-91fa-5673396137e9%40googlegroups.com.

Reply via email to