~~~
package main
/*
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
unsigned char ** f1() {
int i, j;
unsigned char ** original = (unsigned char **)malloc(8);
for(i = 0; i < 8; i++)
{
original[i] = (unsigned char *)malloc(1024);
for(j = 0; j < 1024; j++)
{
original[i][j] = (unsigned char)(j);
}
}
return original;
}
void f2(unsigned char **arr) {
int i, j;
for(i = 0; i < 8; i++)
{
printf("i=%d\n", i);
for(j = 0; j < 1024; j++)
{
printf("%02x", arr[i]);
}
printf("\n\n");
}
}
*/
import "C"
import "fmt"
import "unsafe"
func main() {
dirs := make([][]byte, 8)
for i := 0; i < 8; i++ {
fmt.Println("i=", i)
dirs[i] = make([]byte, 1024)
for j := 0; j < 1024; j++ {
dirs[i][j] = byte(j)
}
fmt.Printf("%x\n", dirs[i])
}
C.f2((**C.uchar)(unsafe.Pointer(&dirs[0][0])))
buf := C.f1()
decodeBuf := uintptr(unsafe.Pointer(buf))
var enBuf [8][1024]byte
for i := 0; i < 8; i++ {
for k := 0; k < 1024; k++ {
tBuf := unsafe.Pointer(decodeBuf)
enBuf[i][k] = *(*byte)(tBuf)
decodeBuf += unsafe.Sizeof(enBuf[i][k])
}
fmt.Printf("%d buf=%x\n", len(enBuf[i]), enBuf[i])
}
}
~~~
这样为什么错了???
从go访问的数据和从c中访问的数据不相同
代码有一个小错误
~~~
package main
/*
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
unsigned char ** f1() {
int i, j;
unsigned char ** original = (unsigned char **)malloc(8);
for(i = 0; i < 8; i++)
{
original[i] = (unsigned char *)malloc(1024);
for(j = 0; j < 1024; j++)
{
original[i][j] = (unsigned char)(j);
}
}
return original;
}
void f2(unsigned char **arr) {
int i, j;
printf("f2\n");
for(i = 0; i < 8; i++)
{
printf("i=%d\n", i);
for(j = 0; j < 1024; j++)
{
printf("%02x", arr[i][j]);
}
printf("\n\n");
}
}
*/
import "C"
import "fmt"
import "unsafe"
func main() {
dirs := make([][]byte, 8)
for i := 0; i < 8; i++ {
fmt.Println("i=", i)
dirs[i] = make([]byte, 1024)
for j := 0; j < 1024; j++ {
dirs[i][j] = byte(j)
}
fmt.Printf("%x\n", dirs[i])
}
C.f2((**C.uchar)(unsafe.Pointer(&dirs[0][0])))
buf := C.f1()
decodeBuf := uintptr(unsafe.Pointer(buf))
var enBuf [8][1024]byte
for i := 0; i < 8; i++ {
for k := 0; k < 1024; k++ {
tBuf := unsafe.Pointer(decodeBuf)
enBuf[i][k] = *(*byte)(tBuf)
decodeBuf += unsafe.Sizeof(enBuf[i][k])
}
fmt.Printf("%d buf=%x\n", len(enBuf[i]), enBuf[i])
}
}
~~~
不知道为什么不能访问???
#1