为了账号安全,请及时绑定邮箱和手机立即绑定

从**字符到蟒蛇列表

从**字符到蟒蛇列表

Go
幕布斯6054654 2022-09-12 20:47:18
我已经解决了这个问题,请参阅问题下面的答案。但我最终发现将GO函数嵌入到Python中是非常愚蠢的。这种嵌入失败主要是因为Go函数几乎不知道何时回收内存资源,从而导致内存泄漏。目前,我意识到将它们组合在一起的最好方法可能是信息交流,就像袜子一样。如果我的想法是错误的,请告诉我任何正确的事情。原始问题:在 C 端,函数返回一个字符串数组(例如 [“i 0”、“i 1”、“i 2”、“i 3”]),类型为 。**char在 Python 端,该输出被读入一个变量(比如说),其类型为**charcArrayPOINTER(c_char_p)我的问题:如何创建一个python列表?即获得cArraypylist == ["i 0","i 1","i 2","i 3"]我还想知道在python中是否有一个值获取操作,就像C中的*操作一样。下面是代码示例:C面(实际去)package main//#include <stdlib.h>import "C"import (    "unsafe")//export TestLoadfunc TestLoad(cstr *C.char) **C.char {    gostr := C.GoString(cstr)    goslice := []string{gostr, "i 0", "i 1", "i 2", "i 3"}    cArray := C.malloc(C.size_t(len(goslice)) * C.size_t(unsafe.Sizeof(uintptr(0))))    defer C.free(unsafe.Pointer(cArray))    temp := (*[1<<30 - 1]*C.char)(cArray)    for k, v := range goslice {        temp[k] = C.CString(v)    }    return (**C.char)(cArray)}func main() {}蟒蛇侧from ctypes import *mylib = cdll.LoadLibrary("./mylib.so")mylib.TestLoad.argtype = c_char_pmylib.TestLoad.restype = POINTER(c_char_p)  # ***Is it possible to have two or more restypes?*** pystr = "hello"                             #  python strb = pystr.encode("utf-8")                   #  convert str to bytesresp = mylib.TestLoad(b)                    #  call CGo function, and get resp typed POINTER(c_char_p)list_len = 5                                #  assume the length of list is known'''TODO'''顺便说一句,单个C或CGO函数是否有可能具有两个或多个返回?我尝试过,但未能成功。感谢您的帮助。
查看完整描述

1 回答

?
缥缈止盈

TA贡献2041条经验 获得超4个赞

溶液:

C 侧 (GO) -- 应注释位置的行defer C.free...

package main


//#include <stdlib.h>

import "C"

import (

    "fmt"

    "unsafe"

)


//export TestLoad

func TestLoad(cstr *C.char) **C.char {

    gostr := C.GoString(cstr)

    fmt.Println("In Go: ", gostr)

    goslice := []string{gostr, "i 0", "i 1", "i 2", "i 3"}

    cArray := C.malloc(C.size_t(len(goslice)) * C.size_t(unsafe.Sizeof(uintptr(0))))

    // defer C.free(unsafe.Pointer(cArray))

    temp := (*[1<<30 - 1]*C.char)(cArray)

    for k, v := range goslice {

        temp[k] = C.CString(v)

    }


    return (**C.char)(cArray)

}


func main() {

}

蟒蛇侧 -- 修改:指针(c_char_p * 5),然后调用 resp.content 来访问每个蟒蛇字节。有关源代码,请参阅示例 #17。

from ctypes import *


mylib = cdll.LoadLibrary("./_mylib.so")

mylib.TestLoad.argtype = c_char_p

mylib.TestLoad.restype = POINTER(c_char_p*5)      


pystr = "Hello, world!"                             

b = pystr.encode("utf-8")                      

resp = mylib.TestLoad(b)  

        

'''**********************************'''

output = []

for seq in resp.contents:

    s = seq.decode("utf-8")

    output.append(s)

    print(s,type(s))

print(output)

'''**********************************'''

一个新的问题出现了:

会评论 // 推迟 C.免费(不安全。指针(cArray))导致C端的内存泄漏在这个例子中?


查看完整回答
反对 回复 2022-09-12
  • 1 回答
  • 0 关注
  • 78 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号