9. Python與C之導入變量

  1. 經過對應類型的類方法in_dll的方式來加載。

    struct Test
    	{
    		int a;
    		int b;
    		Test(int x=5,int y = 6):a(x),b(y){}
    	};
    	extern "C" int hello = 1;
    	extern "C" int * hellop = &hello;
    	extern "C" Test t(1,2);
    	extern "C" void show()
    	{
    		hello = 10;
    	}
    from ctypes import *
    	class Test(Structure):
    		_fields_ = [ ("a",c_int),("b",c_int)]
    	handle = CDLL("./test.so")
    	hello  = c_int.in_dll(handle,"hello")
    	hellop = POINTER(c_int).in_dll(handle,"hellop")
    	ttest  = Test.in_dll(handle,"t")
    	handle.show()
    	print(hello,hellop[0],ttest.a,ttest.b)
  2. 編譯執行python

    g++ -m32 -shared -fPIC -o test.so test.cppcode

    python test.py編譯

相關文章
相關標籤/搜索