Alc*_*ott 3 c python string pointers
我有libx.so
,它导出一个函数和一个全局的char *
,
char *c_ptr = 0;
void foo(char *s)
{
c_ptr = s;
}
Run Code Online (Sandbox Code Playgroud)
在 python 中,我通过两种方式传递str
a ,foo
>>>libx = ctypes.CDLL("./libx.so")
#pass a raw str
>>>libx.foo("string")
#pass a c_char_p object
>>>libx.foo(c_char_p("strng"))
Run Code Online (Sandbox Code Playgroud)
问
1.我认为,libx.foo("string")
将Pythonstr
对象传递给C函数,该函数稍后将字符串分配给char *c_ptr
. 我想知道,调用后会c_ptr
指向该str
对象吗?因为我认为该对象将在调用后被垃圾收集,对吗?"string"
foo
str
"string"
foo
2.两种方式(通过"string"
和c_char_p("string")
)效果有区别吗?它们的作用有什么不同吗?
小智 7
对于任何发现这一点的人来说,Python 3 中的字符串和字节现在是不同的。ctypes 需要一个 bytes 实例才能正确地将参数传递为char*
.
test_lib.get_val(b'Test1', byref(a))
将完整的“Test1”作为 char* 传递给 c 函数
test_lib.get_val('Test1', byref(a))
不会将“Test1”作为 char* 传递,从我的一点点测试来看,它传递了 python 的第一个字母,str
后跟一个空字符。
归档时间: |
|
查看次数: |
6183 次 |
最近记录: |