CGO-How to access C struct pointer correctly

366 views
Skip to first unread message

陈一剑

unread,
Aug 7, 2018, 8:42:26 AM8/7/18
to golang-nuts
package main


import (
   
"fmt"
   
/*
       struct Test{
        int ID;
       };


       struct Test * test(){
        struct Test test;
        test.ID=333;
        return &test;
       };
    */

   
"C"
)


type c
struct {
    ID
int
}
type
Test struct {
    a
string
    b
string
}


func main
() {
   
var b *C.struct_Test=C.test()
    fmt
.Println(b.ID)
}


---------------------------------------------
I want to print 333,but the result is strange.

Thanks
Chen


Jan Mercl

unread,
Aug 7, 2018, 8:55:44 AM8/7/18
to 陈一剑, golang-nuts
On Tue, Aug 7, 2018 at 2:42 PM 陈一剑 <cyj...@gmail.com> wrote:


> I want to print 333,but the result is strange.

The answer is provided by the compiler itself:

jnml@r550:~/src/tmp> cat main.go 
package main

import (
"fmt"
/*
   struct Test{
    int ID;
   };


   struct Test * test(){
    struct Test test;
    test.ID=333;
    return &test;
   };
*/
"C"
)

func main() {
b := C.test()
fmt.Println(b.ID)
}
jnml@r550:~/src/tmp> go run main.go 
# command-line-arguments
./main.go: In function ‘test’:
./main.go:14:6: warning: function returns address of local variable [-Wreturn-local-addr]
      return &test;
      ^
1
jnml@r550:~/src/tmp>
--

-j

Reply all
Reply to author
Forward
0 new messages