是否可以通过ctypes通过引用传递python字符串? [英] Is it possible to pass a python string by reference through ctypes?

查看:225
本文介绍了是否可以通过ctypes通过引用传递python字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,但是我通常很难阅读当前的ctypes文档...

I'm sorry, but I generally have a hard time reading the current ctypes docs...

如果我的C函数需要 const char * 指针,而我知道它既不会修改传入的字符串,也不会在函数调用之外保留对它的引用,这对于直接将指针传递到python字符串的字节。

If I have a C function that takes a const char * pointer, and I know it will neither modify the passed in string, nor keep a reference to it beyond the function call, it really makes sense to pass in a pointer directly to the bytes of a python string.

ctypes是否可以做到这一点?我真的需要 create_string_buffer 并将我的字符串复制到其中吗?

Can ctypes can do this or is it just plain unsupported? Do I really have to create_string_buffer and copy my string into it?

推荐答案


为指针类型c_char_p,c_wchar_p和c_void_p的实例分配新值会更改它们指向的内存位置,而不是内存块的内容(当然不是,因为Python字符串是不可变的) :

Assigning a new value to instances of the pointer types c_char_p, c_wchar_p, and c_void_p changes the memory location they point to, not the contents of the memory block (of course not, because Python strings are immutable):



>>> s = "Hello, World"
>>> c_s = c_char_p(s)
>>> print c_s
c_char_p('Hello, World')
>>> c_s.value = "Hi, there"
>>> print c_s
c_char_p('Hi, there')
>>> print s                 # first string is unchanged
Hello, World
>>>




但是,请注意不要通过
它们到期望
指向可变内存的指针的函数。如果
需要可变的内存块,则ctypes具有
的create_string_buffer函数,其中
以各种方式创建它们。
当前存储块的内容可以通过
的原始属性访问(或更改)
,如果要以
NUL终止的字符串访问它,请使用字符串
属性:

You should be careful, however, not to pass them to functions expecting pointers to mutable memory. If you need mutable memory blocks, ctypes has a create_string_buffer function which creates these in various ways. The current memory block contents can be accessed (or changed) with the raw property, if you want to access it as NUL terminated string, use the string property:

使用ctypes教程。我从中收集的信息是,只有函数可以与 const char * 一起使用,传入python字符串才有效。请记住,它不会有空终止符。

Says the ctypes tutorial. What I gather from this is that only if the function would work with a const char*, would passing in the python string be valid. Keep in mind, it won't have a null termination.

无论如何,我建议使用 create_string_buffer

I'd suggest using create_string_buffer anyhow.

这篇关于是否可以通过ctypes通过引用传递python字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆