从cgo检索指针时获取错误或空值

2024-06-16 10:07:07 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,在我的cgo代码中,我将从cgo返回一个指向python的指针,然后尝试使用ctypes.from_address()函数从python中的C结构指针访问值,但我得到了错误

有时它为第一个变量提供正确的值,但第二个变量为空。有时,第一个变量给出的是随机值,而不是正确的值,第二个变量的变量仍然是空的,反之亦然

我怎样才能解决这个问题?或者如何正确访问这些结构的值?
cgo代码:

package main

/*
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

typedef struct {
    char *response;
    char *response2;
} Resp;
*/
import "C"

//export getResponse
func getResponse() unsafe.Pointer {
    s := (*C.Resp)(C.calloc(C.sizeof_Resp, 1))
    defer C.free(unsafe.Pointer(s))

    s.response = C.CString("HELLO WORLD, HELLO EVERYONE")
    defer C.free(unsafe.Pointer(s.response))

    s.response2 = C.CString("TEST TEST TEST TEST TEST TEST")
    defer C.free(unsafe.Pointer(s.response2))

    return unsafe.Pointer(s)

}

Python代码函数:

from ctypes import *
from ctypes import cdll
import gc
import datetime

class Resp(Structure):
    _fields_ = [
        ('response', c_char_p),
        ('response2', c_char_p)
    ]

for i in range(20):
    lib = cdll.LoadLibrary(./cgotest2.so)

    lib.getResponse.restype = c_void_p
    resp = Resp.from_address(lib.getResponse())

    print(resp.response)
    print(resp.response2)

我得到的是随机值,有时是空白值或正确值。 这就是我得到的:

response: b'HELLO WORLD, HELLO EVERYONE'
response2: b''
response: b''
response2: b'[?\x94\x87\xfc\x07'
response: b''
response2: b'\xf4F\x96\x87\xfc\x07'
response: b''
response2: b'[\r\x94\x87\xfc\x07'
response: b''
response2: b'TEST TEST TEST TEST TEST TEST'

我不知道为什么它会给我空白值或随机值。我的cgo代码有什么问题吗?或者是我用ctypes在python中传递它的方式有什么问题吗


Tags: 代码fromtestimporthelloincluderesponsectypes