Python-ctypes-如何调用函数和访问结构字段
Python - ctypes - How to call functions and access struct fields?
我有一个C库:
smart_string.h:
typedef struct SmartString {
unsigned string_len;
unsigned alloc_len;
char *str;
char *str_terminator;
} SmartString;
SmartString *SmartString_new(char *str);
... definitions of more functions ...
该实现位于名为smart_string.c.的文件中
我需要一个运行SmartString_new()
函数和访问返回结构指针的字段的指南。
谁能教我怎么做吗?
谢谢!
回答自己并与您分享知识:
首先,需要从C文件创建一个共享库:
gcc -shared -fpic smart_string.c -o SmartString.so
然后,使用以下Python代码(有关每个已完成操作的解释,请参见注释):
注意:上面API中显示的char*
是C可编辑字符串,而const char*
是只读字符串。由于C API需要char*
而不是const char*
,因此我们必须向其传递一个可变字符串,以便C代码可以对其进行编辑。默认情况下,Python字符串是不可变的。因此,我们在这里使用create_string_buffer()
函数
python_smart_string.py:
import ctypes
from ctypes import *
# Defining the python type that represents the C SmartString
# It must extend the 'Structure' class
# Structure, c_uint, c_char_p, etc. were imported from ctypes
class SmartString(Structure):
_fields_=[("string_len",c_uint),
("alloc_len",c_uint),
("str",c_char_p),
("str_terminator", c_char_p)]
# Loading the C shared lib I've just compiled
smartstring_lib = ctypes.CDLL('SmartString.so')
# Defining pointer to the SmartString_new() function
SmartString_new = smartstring_lib.SmartString_new
# Declaring the function return type - a pointer to a SmartString object - just like in the C code
SmartString_new.restype = POINTER(SmartString)
# Declaring list of parameter types. In this case, the list contains only one item,
# as the function has only one parameter
SmartString_new.argtypes = [c_char_p]
# Calling the SmartString_new() function. Expecting to get a pointer to SmartString object into 'my_str'
# The API requires a MUTABLE string, so create_string_buffer() is used here
# The reference to this string is not saved, as I don't care if it is modified by the C code
my_str = SmartString_new(create_string_buffer('my nice string'))
# Printing fields of the dereferenced returned value (dereferencing is done using '.contents')
print my_str.contents.string_len
print my_str.contents.alloc_len
print my_str.contents.str
print my_str.contents.str_terminator
相关文章:
- 使用不带参数的函数访问结构元素
- 删除目录函数访问被拒绝
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 如何使用 C++ 中的继承函数访问派生类中的局部变量
- 我想要一个具有子函数的函数访问相同的命名函数,而不使用它取决于其子类的类
- 有没有办法通过 main 函数访问受保护的矢量大小而无需将其转换为公共?
- 如何在C++通过公共函数访问私有函数成员?
- 限制variadic模板类中的构造函数访问
- 从析构函数访问模板类构造函数的参数,可以吗?
- 变量 z 无法从其他函数访问变量 x
- 从静态成员函数访问私有非静态类变量 - C++
- 如何在 C++ 中从 void 返回函数访问变量
- 在类中使用映射并通过其他类的 get() 和 set() 函数访问值
- 无法从另一个函数访问文件范围变量的内容
- 是否可以从 C++ 中的构造函数访问对象名称?
- 使用C 中的共享_ptr从公共静态成员函数访问私有构造函数
- 使用静态成员函数访问静态数据成员
- 为什么我们可以从 C++ 中的成员函数访问 non_member 函数
- 如何使用 c++ 中的函数访问全局变量?
- 如何从 C++ 中的主函数访问类中的私有构造函数?