5.Python對應C的結構體,聯合體

  1. 結構體

    通常結構體都繼承自這幾個類。python

    BigEndianStructure, LittleEndianStructure,Structure數組

    而後屬性名爲_fields_的集合,集合的單個元素是一個二元組。指針

    python代碼

    from ctypes import *
    	class Test(Structure):
    	_fields_ = [("a",c_int),("b",c_int)]
    	handle = CDLL("./test.dll")
    	handle.test.restype = Test
    	handle.test.argtypes= [c_int]
    	ret = handle.test(2)
    	print(ret.a,ret.b)
    	"""
    	1 2
    	hello test2
    	[Finished in 0.1s]
    	"""

    C++代碼

    #include<stdio.h>
    	struct Test
    	{
    		int a;
    		int b;
    		Test(int x = 1,int y = 2)
    		{
    		a = x;
    		b = y;
    		}
    	};
    	extern "C"  Test test(int n)
    	{
    		printf("hello test%d\n",n);
    		return Test();
    	}

    編譯代碼g++ -shared -fPIC -m32 -o test.dll test.cpp

  2. 結構體指針 byref(struct),生成一個指針,通常用做傳入參數。rest

    pointer(struct),生成一個指針,這個是用來直接生成的,相似 int* = (&int_var).經常使用於生成一個指針code

    POINTER(type)(init_value),經常使用語生成一個數組。繼承

    生成數組長度爲1的指針POINTER(c_int)(c_int(0))it

    生成數組長度爲n的指針POINTER(c_int)( (c_int*n)()),類比C++的POINTER<c_int>(new c_int[n]())io

  3. 對齊方式

    經過屬性_pack_設置,和#param pack()同樣。正整數。編譯

相關文章
相關標籤/搜索