日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python ctypes 指针_Python Ctypes传递.h文件中定义的结构指针。

發布時間:2023/12/4 python 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python ctypes 指针_Python Ctypes传递.h文件中定义的结构指针。 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

我認為您可能缺少的是確切地知道您希望分配結構內存的位置。下面的c代碼提供了一個為struct分配內存并返回指向它的指針的函數(new_struct())。#include

#include

#include

typedef struct {

int a;

int b;

} my_struct;

my_struct *new_struct()

{

my_struct *struct_instance = (my_struct *)malloc(sizeof(my_struct));

memset(struct_instance, 0, sizeof(my_struct));

return struct_instance;

}

int modify_struct(my_struct *ms) {

ms->a = 1;

ms->b = 2;

return 0;

}

void print_struct_c(my_struct *ms) {

printf("my_struct {\n"

" a = %d\n"

" b = %d\n"

"}\n", ms->a, ms->b);

}

從Python獲取指針,調用執行分配的C函數,然后可以將其傳遞給將其作為參數的其他C函數。import ctypes

lib_file_path = <<< path to lib file >>>

# Very simple example of how to declare a ctypes structure to twin the

# C library's declaration. This doesn't need to be declared if the Python

# code isn't going to need access to the struct's data members.

class MyStruct(ctypes.Structure):

_fields_ = [('a', ctypes.c_int),

('b', ctypes.c_int)]

def print_struct(s):

# Print struct that was allocated via Python ctypes.

print("my_struct.a = %d, my_struct.b = %d" % (s.a, s.b))

def print_struct_ptr(sptr):

# Print pointer to struct. Note the data members of the pointer are

# accessed via 'contents'.

print("my_struct_ptr.contents.a = %d, my_struct_ptr.contents.b = %d"

% (sptr.contents.a, sptr.contents.b))

my_c_lib = ctypes.cdll.LoadLibrary(lib_file_path)

# If you don't need to access the struct's data members from Python, then

# it's not necessary to declare MyStruct above. Also, in that case,

# 'restype' and 'argtypes' (below) can be set to ctypes.c_void_p instead.

my_c_lib.new_struct.restype = ctypes.POINTER(MyStruct)

my_c_lib.modify_struct.argtypes = [ctypes.POINTER(MyStruct)]

# Call C function to create struct instance.

my_struct_c_ptr = my_c_lib.new_struct()

print_struct_ptr(my_struct_c_ptr)

my_c_lib.modify_struct(my_struct_c_ptr)

print_struct_ptr(my_struct_c_ptr)

# Allocating struct instance from Python, then passing to C function.

my_struct_py = MyStruct(0, 0)

print_struct(my_struct_py)

my_c_lib.modify_struct(ctypes.byref(my_struct_py))

print_struct(my_struct_py)

# Data members of Python allocated struct can be acessed directly.

my_struct_py.a = 555

my_c_lib.print_struct_c(ctypes.byref(my_struct_py)) # Note use of 'byref()'

# to invoke c function.

上面的代碼已經更新,包括如何通過Python分配結構實例的示例,以及如何訪問C已分配或Python分配結構的數據成員(請注意打印函數中的差異)。

總結

以上是生活随笔為你收集整理的python ctypes 指针_Python Ctypes传递.h文件中定义的结构指针。的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。